简体   繁体   中英

operation on dataframe factor columns

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM