Home > Mobile >  creating a new column based on other columns in R
creating a new column based on other columns in R

Time:11-24

I have a data frame as:

pred

   V1 V2 V3
2   0  1  0
4   0  0  1
5   0  0  1
8   0  0  1
11  0  1  0
16  0  1  0
20  1  0  0
21  0  1  0
24  0  1  0
26  0  1  0
31  0  0  1
32  1  0  0
34  1  0  0

I want to create a 4th column that is equal to "Intermediate" if V1 is equal to 1, is labeled as "Long" if V2 is equal to 1, and "Short" if V3 is equal to 1.

Thank you

CodePudding user response:

Base R solution. With df==1 we check which elements of the data frame are equal to 1, return the indices of the matches, and then match with a new vector with the desired names.

tmp=which(df==1,arr.ind=T)    
tmp=tmp[order(tmp[,"row"]),]
c("Intermediate","Long","Short")[tmp[,"col"]]

 [1] "Long"         "Short"        "Short"        "Short"        "Long"        
 [6] "Long"         "Intermediate" "Long"         "Long"         "Long"        
[11] "Short"        "Intermediate" "Intermediate"

CodePudding user response:

Here is another base R approach. If df is your data.frame, you can convert it to a matrix, multiply by a sequence from 1 to number of columns, and create a factor with the desired labels (in the same order as the columns).

df$new <- factor(as.matrix(df) %*% (1:ncol(df)), 
                 labels = c("Intermediate", "Long", "Short"))

Output

R> df
   V1 V2 V3          new
1   0  1  0         Long
2   0  0  1        Short
3   0  0  1        Short
4   0  0  1        Short
5   0  1  0         Long
6   0  1  0         Long
7   1  0  0 Intermediate
8   0  1  0         Long
9   0  1  0         Long
10  0  1  0         Long
11  0  0  1        Short
12  1  0  0 Intermediate
13  1  0  0 Intermediate

CodePudding user response:

Maybe you can add new column using the code below

> c("Intermediate", "Long", "Short")[rowSums(col(df) * df)]
 [1] "Long"         "Short"        "Short"        "Short"        "Long"        
 [6] "Long"         "Intermediate" "Long"         "Long"         "Long"
[11] "Short"        "Intermediate" "Intermediate
  • Related