在循环制作汇总表中,通过根据条件填充数据

时间:2018-10-25 10:40:10

标签: r for-loop dataframe dplyr

让我们说我有一个循环,在每个循环中都有一个这样的表结果:

  #Looping Result Data
  value <- c("A1", "A2", "A3", "A4")
  value.dat <- rep("Yes", 4)
  n <- c(4, 1, 2, 4 )
  resloop <- data.frame(value, value.dat, n)

在循环中,我希望每个循环都有(最后)摘要表,该表如下所示:

Country <- rep(c("Germany", "France"), each=12)
Sectoral <- rep(c("A-A", "B-A", "B-B", "A-C", "C-B", "C-C"), times=4)
Connection <- rep(c("Yes", "No"), each=6)
Freq.Ind <- NA
t.sum<- data.frame(Country, Sectoral, Connection, Freq.Ind)

Freq.Ind应该由resloop中n最多的值填充(因此,如果有相同的大n则可以大于一个值)

因此,如果现在处于循环中:

 i<-"Germany"
 j<-"A-A"

我要在Freq.Ind第一行中填充:A1,A4

我已经尝试过类似的操作,但是还是有问题:((newbie)

 t.sum[t.sum$Country == i && t.sum$Sectoral == j && t.sum$Connection ==  "Yes", "Freq.Ind"]<- as.character(resloop$value[resloop$n==max(resloop$n)])
t.sum$Freq.Ind <- ifelse( t.sum$Country == i & t.sum$Sectoral == j & t.sum$Connection == "Yes",  as.character(resloop$value[resloop$n==max(resloop$n)]), next )


 t.sum %>% 
     mutate(Freq.Ind=replace(Freq.Ind, Country == i & Sectoral == j &  Connection == "Yes" ,as.character(resloop$value[resloop$n==max(resloop$n)])))

谢谢

1 个答案:

答案 0 :(得分:0)

我已经从审判中得到了这个(到目前为止)

as.character(resloop$value[resloop$n==max(resloop$n)])-> themax
themax <- cbind(themax)
library(stringr)
str_c(themax, collapse = ",") ->themax

t.sum %>% 
mutate(Freq.Ind=replace(Freq.Ind, Country == i & Sectoral == j & Connection == "Yes" ,themax))

我确定还有更简单的方法,随时分享。