简体   繁体   English

将数据框的某些元素移到新列中(R中)

[英]Moving certain elements of data frame into new columns (in R)

I have a data frame in R looking like this: 我在R中有一个数据框,如下所示:

jiz <- data.frame(Type=c("X","B","B","B","B","X","B"),
                  Action=c("both","1","2","2","1","both","1"))

Type is either X or B, and Action decides what type of action (either action 1 or 2) should be taken on the variables in Type. Type是X或B,并且Action决定应对Type中的变量采取哪种类型的操作(操作1或2)。 If type is "X", both actions are always to be taken, and if type is "B", either action 1 or action 2 are to be taken. 如果类型为“ X”,则始终要执行两个动作,如果类型为“ B”,则将要执行动作1 动作2。

Now we add two columns: 现在我们添加两列:

jiz[c("1","2")]<-NA

Now, I want "X" to go into both the new columns, since both actions were taken and "B" to go into either one of the new column - depending on what action was taken, such that any R code would make this new data frame: 现在,我希望“ 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))

Note that if "B" had action 2 - B was put into the new column "2" - and a 0 was put in column "1". 请注意,如果“ B”具有动作2-B被放入新列“ 2”中-并且0被放入列“ 1”中。

Here's an approach: 这是一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM