r - Creating a factor/categorical variable from 4 dummies -



r - Creating a factor/categorical variable from 4 dummies -

i have info frame 4 columns, let's phone call them v1-v4 , 10 observations. 1 of v1-v4 1 each row, , others of v1-v4 0. want create new column called newcol takes on value of 3 if v3 1, 4 if v4 1, , 0 otherwise.

i have many sets of variables v1-v4 solution short possible easy replicate.

this 4 columns add together 5th using matrix multiplication:

> cbind( mydf, newcol=data.matrix(mydf) %*% c(0,0,3,4) ) v1 v2 v3 v4 newcol 1 1 0 0 0 0 2 1 0 0 0 0 3 0 1 0 0 0 4 0 1 0 0 0 5 0 0 1 0 3 6 0 0 1 0 3 7 0 0 0 1 4 8 0 0 0 1 4 9 0 0 0 1 4 10 0 0 0 1 4

it's generalizable getting multiple columns.... need rules. need create matric the same number of rows there columns in original info , have 1 column each of new factors needed build each new variable. shows how build 1 new column sum of 3 times 3rd column plus 4 times fourth, , new column 1 times first , 2 times second.

> cbind( mydf, newcol=data.matrix(mydf) %*% matrix(c(0,0,3,4, # first set of factors 1,2,0,0), # sec set ncol=2) ) v1 v2 v3 v4 newcol.1 newcol.2 1 1 0 0 0 0 1 2 1 0 0 0 0 1 3 0 1 0 0 0 2 4 0 1 0 0 0 2 5 0 0 1 0 3 0 6 0 0 1 0 3 0 7 0 0 0 1 4 0 8 0 0 0 1 4 0 9 0 0 0 1 4 0 10 0 0 0 1 4 0

r r-factor

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -