CLID <-c(1,2,1,2)
SUBJ<- c(1,2,3,4)
df<-cbind.data.frame(CLID,SUBJ)
for (TRT in df$CLID){
for (SUB in df$SUBJ){
if (CLID == 1 & SUBJ==1) {
df$TRT <- paste("A")
} else if (CLID==1 & SUBJ==2) {
df$TRT <- paste("B")
}else if (CLID==1 & SUBJ==4) {
(TRT <- "C")
df$TRT <- paste("C")
}else {
df$TRT <- paste("NA")
}
}
}
我试图用Subject和CLID的独特组合创建一个新列。预期的代码正在创建新的列,但输出与预期的不一样。它应该是两者的结合,但事实并非如此。如何确定所创建的新列是这两个条件的组合?
预期结果是这样
CLID <-c(1,2,1,2)
SUBJ<- c(1,2,3,4)
TRT<-c("A","NA","NA","C")
df_expected<-cbind.data.frame(CLID,SUBJ,TRT)
答案 0 :(得分:1)
您可以尝试一下。但是,它与您的预期输出不匹配。如果CLID == 2和SUBJ == 4,则TRT应该为C。
library(dplyr)
df %>%
mutate(TRT = case_when(
CLID == 1 & SUBJ == 1 ~ "A",
CLID == 1 & SUBJ == 2 ~ "B",
CLID == 1 & SUBJ == 4 ~ "C"
))
#> CLID SUBJ TRT
#> 1 1 1 A
#> 2 2 2 <NA>
#> 3 1 3 <NA>
#> 4 2 4 <NA>
编辑
这里是执行相同操作的循环
for(i in 1:nrow(df)){
if(df$CLID[i] == 1 & df$SUBJ[i] == 1){
df$TRT[i] <- "A"
}
else if(df$CLID[i] == 1 & df$SUBJ[i] == 2){
df$TRT[i] <- "B"
}
else if(df$CLID[i] == 1 & df$SUBJ[i] == 4){
df$TRT[i] <- "C"
}
else{
df$TRT[i] <- NA
}
}
df
#> CLID SUBJ TRT
#> 1 1 1 A
#> 2 2 2 <NA>
#> 3 1 3 <NA>
#> 4 2 4 <NA>
或使用嵌套ifelse
语句的另一个选项。
df$TRT <- ifelse(df$CLID == 1 & df$SUBJ == 1, "A",
ifelse(df$CLID == 1 & df$SUBJ == 2, "B",
ifelse(df$CLID == 1 & df$SUBJ == 4, "C", NA)))
df
#> CLID SUBJ TRT
#> 1 1 1 A
#> 2 2 2 <NA>
#> 3 1 3 <NA>
#> 4 2 4 <NA>