我在R中有一个数据框,如下所示:
jiz <- data.frame(Type=c("X","B","B","B","B","X","B"),
Action=c("both","1","2","2","1","both","1"))
Type为X或B,Action决定应对Type中的变量采取何种类型的操作(操作1或2)。如果type为“X”,则始终采取两种操作,如果type为“B”,则执行操作1 或操作2。
现在我们添加两列:
jiz[c("1","2")]<-NA
现在,我希望“X”进入两个新列,因为两个操作都被采取,“B”进入新列中的任何一个 - 取决于采取了什么操作,这样任何R代码都会产生这个新的数据框:
jiz.new <- data.frame(Type=c("X","B","B","B","B","X","B"),
Action=c("both","1","2","2","1","both","1"),
"1"=c("X","B",0,0,"B","X","B"),
"2"=c("X",0,"B","B",0,"X",0))
请注意,如果“B”有动作2 - B被放入新列“2” - 并且0被放入“1”列。
答案 0 :(得分:2)
这是一种方法:
transform(jiz, "1" = ifelse(Action != "2", as.character(Type), "0"),
"2" = ifelse(Action != "1", as.character(Type), "0"))
Type Action X1 X2
1 X both X X
2 B 1 B 0
3 B 2 0 B
4 B 2 0 B
5 B 1 B 0
6 X both X X
7 B 1 B 0