This is minimum reproducible example, but my real data is really huge so I cannot do it manually
id<-1:4
mathpass_1<-c("pass","fail","pass","fail")
mathpass_2<-c("fail","fail","fail","fail")
mathpass_3<-c("fail","fail","pass","pass")
mathpass_4<-c("fail","fail","pass","fail")
math<-data.frame(id,mathpass_1,mathpass_2,mathpass_3,mathpass_4)
so, the data is like this
> math
id mathpass_1 mathpass_2 mathpass_3 mathpass_4
1 1 pass fail fail fail
2 2 fail fail fail fail
3 3 pass fail pass pass
4 4 fail fail pass fail
the Id is student's Id. I want to make an additional column ( binary variable) if a student get at least one pass, they will have "pass" and if a student did not get any pass, they will have "fail"
so, I want to make a column "pass" like this, but I made it manually.
id<-1:4
mathpass_1<-c("pass","fail","pass","fail")
mathpass_2<-c("fail","fail","fail","fail")
mathpass_3<-c("fail","fail","pass","pass")
mathpass_4<-c("fail","fail","pass","fail")
pass<-c("pass","fail","pass","pass")
math<-data.frame(id,mathpass_1,mathpass_2,mathpass_3,mathpass_4,pass)
> math
id mathpass_1 mathpass_2 mathpass_3 mathpass_4 pass
1 1 pass fail fail fail pass
2 2 fail fail fail fail fail
3 3 pass fail pass pass pass
4 4 fail fail pass fail pass
However, my real data is really huge that I cannot do manually. How can I do this with code? (non-manual way)
CodePudding user response:
Try ifelse(rowSums(math[,-1]=="pass")>0,"pass","fail")
.
CodePudding user response:
You may try
library(dplyr)
math %>%
mutate(pass = ifelse(rowSums(across(is.character, ~.x == "pass")) >0, "pass", "fail"))
id mathpass_1 mathpass_2 mathpass_3 mathpass_4 pass
1 1 pass fail fail fail pass
2 2 fail fail fail fail fail
3 3 pass fail pass pass pass
4 4 fail fail pass fail pass