我有一个类似这样的数据集:
col_a col_b col_c
1 abc_boy 1
2 abc_boy 2
1 abc_girl 1
2 abc_girl 2
我只需要根据col_b
and col_c
,然后更改中的值col_c
,就像这样:
df[grep("_boy$",df[,"col_b"]) & df[,"col_c"]=="1","col_c"] <- "yes"
但上面的代码并不好,因为第一个条件和第二个条件不是来自同一组。
我可以通过使用显式循环以愚蠢的方式完成此操作,或者进行“两层”子集设置,如下所示:
df.a <- df[grep("_boy$",df[,"col_b"]),] #1
df.b <- df[grep("_boy$",df[,"col_b"],invert=TRUE),] #2
df.a <- df.a[df.a[,"col_c"]=="1","col_c"] <- "yes" #3
df.a <- df.a[df.a[,"col_c"]=="2","col_c"] <- "no" #4
df <- rbind(df.a,df.b) #5
但我不想这样做,谁能启发我如何“合并”#1
and #3
?谢谢。