Gen variable conditional on other variables from a different dataframe

江枫思渺然 提交于 2020-01-05 23:45:08

问题


I Have DF1:

c01 p01 c02 p02 c03 p03 c04 p04
1   0   1   20  1   33  1   49
2   3   2   21  2   34  2   50
3   4   3   21  3   38  3   50
4   6   4   23  4   40  4   51
5   7   5   24  5   41  5   53
6   9   6   27  6   41  6   54
7   11  7   29  7   41  7   55
8   15  8   31  8   43  8   57
9   15  9   33  9   47  9   57
10  16  10  33  10  49  10  60

And i Have DF2:

type    round
A        1
B        1
A        2
B        2
A        3
B        3
A        4
B        4

What i want is to generate a new variable in DF2 that goes like:

 DF2$g1<- if(DF2$round==1, 0)
DF2$g2<- if(c01==4 & round==1,DF2$p01)
DF2$g3<- if(c01==4 & round==2,DF2$p02)
DF2$g4<- if(c01==4 & round==3,DF2$p03)
  DF2$g5<- if(c01==4 & round==4,DF2$p04)
  DF2$g6<- if(c01==4 & round==5,DF2$p05)

So DF2 becomes:

type    round       g
A        1          6
B        1          6
A        2          23
B        2          23
A        3          40
B        3          40
A        4          50
B        4          50

Is there a way that i can loop this? In the original dataframe, i have 40 rounds, e C01 to C40 and P01 to P40

来源:https://stackoverflow.com/questions/53330494/gen-variable-conditional-on-other-variables-from-a-different-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!