0

I dont want to perform operation in a loop,My data look like this

 dfU[4:7]
      vNeg neg pos vPos
 1      0  35  28    0
 2      0  42  26    0
 3      0  77  59    0
 4      0  14  24    0
 5      0  35  45    0
 6      0  17  12    0
 7      0  31  23    0
 8      0  64  52    1
 9      0  15  17    0
 10     0  21  29    0

when i performed certain operation like this but getting an wrong result may be just because of conversion i tried with with and transform also but getting an error not meaningful for factors

  b<-as.numeric(((as.numeric(dfU[,4])*-5)+(as.numeric(dfU[,5])*-2)+(as.numeric(dfU[,6])*2)+(as.numeric(dfU[,7])*5)))
  b 
  [1] -14 -32 -16  18   8  -8 -18  -7   6  14  24  -9   0 

error may be just because of this when i am converting integer to numeric

   typeof(dfU[,4])
   [1] "integer"
   as.numeric(dfU[,4])
   [1] 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1
   k<-transform(dfU, (vNeg*(-5))+(neg*(-2))+(pos*2)+(vPos*5))
   not meaningful for factors

i want the 8th column in a dataframe to be as score and i want to avoid the loop ,Is their any better way to perform operation on columns,any help in this direction,thanks.

Frank
  • 66,179
  • 8
  • 96
  • 180
Aashu
  • 1,247
  • 1
  • 26
  • 41
  • 1
    You may have a look [here](http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information). Also learn about `str`. – Henrik Oct 22 '13 at 08:32
  • 1
    Please provide your data using `dput(dfU)`. The issue is you have factor type vectors that you're trying to perform numeric operations on. – Thomas Oct 22 '13 at 08:32
  • How do you create your data.frame? do you read it? – agstudy Oct 22 '13 at 09:50
  • hey @agstudy i created data.frame by cbind operation on dfU,thanks – Aashu Oct 22 '13 at 09:53

1 Answers1

1

The best would be to avoid having the 4th. column as factor if this is not what to you want to. Still, a workaround is using as.numeric(as.character( )). Assume "a" is your 4th column, your situation is this:

> a <- as.factor(c(rep(0,7),1,rep(0,2)))
> a
 [1] 0 0 0 0 0 0 0 1 0 0
Levels: 0 1
> as.numeric(a)
 [1] 1 1 1 1 1 1 1 2 1 1

And the workaround does:

> as.numeric(as.character(a))
 [1] 0 0 0 0 0 0 0 1 0 0
albifrons
  • 303
  • 2
  • 9