r - Creating a factor/categorical variable from 4 dummies -
I have a data frame with four columns, let's call them V1-V4 and 10 observations. For each row there is 1 of V1-V4, and the second 0 of V1-V4. I want to create a new column named Newcoll which takes the value of 3 if V3 is 1, 4 if V4 is 1, and 0 otherwise
To do this I have several variables V1-V4 To do this for sets, so that I would like to reduce the solution as little as possible so that it is easy to repeat.
This makes it to add five by using the matrix multiplication for 4 columns:
& gt; Cbind (mydf, newcol = data.matrix (mydf)% *% c (0,0,3,4) V1V2V3V4Nuke 1 1 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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 1 4 10 0 0 0 1 4 This is normal for getting multiple columns ... we need the rules. You need to create a matrix with lines of the same number because the original data has columns and there is a column for each new factor necessary to create each new variable. It shows how to create a new column from 3 times the fourth column and 4 to 4 times the amount, and the second time to be created once and for the second time once.
& gt; Cbind (mydf, newcol = data.matrix (mydf)% *% matrix (C (0,0,3,4, # first factor of factor # 1,2,0,0), # seconds set ncol = 2) V1 V2V3V4 Nuclei1Newaul 1 1 0 0 0 1 2 1 0 0 0 0 1 3 0 1 0 0 2 4 0 1 0 0 2 5 0 0 1 0 3 0 6 0 0 1 0 3 0 7 0 0 1 4 0 8 0 0 1 4 0 9 0 0 0 1 4 0 10 0 0 0 1 4 0
Comments
Post a Comment