简体   繁体   中英

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

I have a data frame in R looking like this:

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. 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.

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:

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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