irene123
irene123

Reputation: 11

How do you make a new factor column based on other columns in r?

I have a data set that looks like this

 ID   Group 1   Group 2   Group 3     Group 4
 1     1          0         1          0 
 2     0          1         1          1
 3     1          1         0          0
 .
 .
 .
 100    0         1         0          1

I want to make another column lets say Group 5 where if the condition of Group 1 is 1 then Group 5 would be 1. If Group 2 = 1, then Group 5 = 2. If Group 3 = 1, then Group 5 = 3, and if Group 4 = 1, then Group 5 = 4. How do I do this?

I tried these lines of code, but I seem to be missing something.

 Group5 <- data.frame(Group1, Group2, Group3, Group4, stringsAsFactors=FALSE)

 df$Group5 <- with(finalmerge, ifelse(Group1 %in% c("1", "0"), 
                              "1", ""))

Any advice would be helpful, thanks in advance.

Upvotes: 1

Views: 227

Answers (1)

langtang
langtang

Reputation: 24722

You could use which.max(), and apply this to each row.

df["Group_5"] <- apply(df[, -1], 1, which.max)

Output:

  ID Group_1 Group_2 Group_3 Group_4 Group_5
1  1       0       0       0       1       4
2  2       0       1       0       0       2
3  3       0       0       1       0       3
4  4       1       0       0       0       1

Input:

df = structure(list(ID = c(1, 2, 3, 4), Group_1 = c(0, 0, 0, 1), Group_2 = c(0, 
1, 0, 0), Group_3 = c(0, 0, 1, 0), Group_4 = c(1, 0, 0, 0)), class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 1

Related Questions