R 在不同的数据帧中使用条件变量创建新变量
我有以下数据帧 df1: df2: 我需要df1中的一列,p,如果round=1,它等于0,如果round=2,它等于p01的maxvalue,如果round=3,它等于p02的maxvalue 在实际数据中,在df1中我有38轮,380行,在df2中我有20行(每行代表唯一的mun)。我尝试了以下循环:R 在不同的数据帧中使用条件变量创建新变量,r,dataframe,conditional,R,Dataframe,Conditional,我有以下数据帧 df1: df2: 我需要df1中的一列,p,如果round=1,它等于0,如果round=2,它等于p01的maxvalue,如果round=3,它等于p02的maxvalue 在实际数据中,在df1中我有38轮,380行,在df2中我有20行(每行代表唯一的mun)。我尝试了以下循环: p <-matrix(0, nrow=380,ncol=1) for(i in 2:38){ p <- if(round==i) max(p[[i-1]] %in% df2
p <-matrix(0, nrow=380,ncol=1)
for(i in 2:38){
p <- if(round==i) max(p[[i-1]] %in% df2)
}
p使用dplyr
。如果您可以基于mun1或mun2和mun合并df1和df2,它将起作用
df %>%
left_join(df2, by = c("mun1" = "mun")) %>% #Merging the data
mutate(P = ifelse(round == 1, 0, #Applying the condition
ifelse(round == 2, max(p01),
ifelse(round == 3, max(p02), NA))))
round mun1 mun2 p01 p02 p03 P
1 1 SP PA 3 4 7 0
2 1 RJ PR 0 3 4 0
3 1 BH BA 3 6 9 0
4 2 BA SP 0 1 1 3
5 2 PR BH 1 4 5 3
6 2 PA RJ 1 2 3 3
7 3 RJ BH 0 3 4 6
8 3 PA PR 1 2 3 6
9 3 SP BA 3 4 7 6
即使df1和df2具有不同的维度,这也会起作用?是的,即使df1和df2具有不同的列数和行数,它也会起作用。看?左键连接
。
p <-matrix(0, nrow=380,ncol=1)
for(i in 2:38){
p <- if(round==i) max(p[[i-1]] %in% df2)
}
df %>%
left_join(df2, by = c("mun1" = "mun")) %>% #Merging the data
mutate(P = ifelse(round == 1, 0, #Applying the condition
ifelse(round == 2, max(p01),
ifelse(round == 3, max(p02), NA))))
round mun1 mun2 p01 p02 p03 P
1 1 SP PA 3 4 7 0
2 1 RJ PR 0 3 4 0
3 1 BH BA 3 6 9 0
4 2 BA SP 0 1 1 3
5 2 PR BH 1 4 5 3
6 2 PA RJ 1 2 3 3
7 3 RJ BH 0 3 4 6
8 3 PA PR 1 2 3 6
9 3 SP BA 3 4 7 6