【问题标题】:Converting list from lapply to data frame将列表从 lapply 转换为数据框
【发布时间】:2018-06-11 03:04:03
【问题描述】:

我无法将列表从 lapply 转换为数据框。我的最终输出 xx 接近于我正在寻找的东西,但不完全是。现在是对 10 个变量的 2 次观察。每个观察都是 280 个列表,但我希望我的最终数据框是 10 个变量的 560 个观察,所以只是列表扩展并相互堆叠。感谢您的帮助。

cid_station=data.frame(cid=1:280,station=sample(1:10,size=280,replace=T))

cid=unique(cid_station$cid)

july = rbind(cid_station[rep(1:280,450),])
july$resid=rnorm(n=nrow(july))

w1=data.frame(station=sample(1:10,size=2400,replace=T),
                   kwhhat=rnorm(n=2400,mean=50,sd=10), year=1)
w2=data.frame(station=sample(1:10,size=2400,replace=T),
              kwhhat=rnorm(n=2400,mean=500,sd=10), year=2)
weather= rbind(w1,w2)

iteration=(1:10)
year=(1:2)


x=lapply(iteration,function(z){

  i=lapply(year,function(yr){
    subset_y=weather[weather$year==yr,]

      peaks=lapply(cid,function(id){
            subset_r=july[july$cid==id,"resid"]
            subset_s=unique(july[july$cid==id,"station"])
            subset_w=subset_y[subset_y$station==subset_s,]
            subset_w$resid=sample(subset_r,size=nrow(subset_w),replace=T)
            subset_w$kw=subset_w$kwhhat+subset_w$resid
            peak=max(subset_w$kw)
          })
      })
  })

xx=as.data.frame(do.call(cbind, x))

【问题讨论】:

    标签: r


    【解决方案1】:

    我觉得您的代码中必须有一些优化可能,但我对您想要做什么还不够清楚。就是说 - purrr 包中的 map_dfc 函数应该可以为您提供您想要的。

    xx <- map_dfc(x, unlist)
    

    【讨论】:

    • map_dfc(x, unlist) 也可以。
    • 知道为什么会出现以下错误吗? “cbind_all(x) 中的错误:与 STRSXP 不兼容:[type=NULL]”
    • @hpesoj626 你是对的 - 这是以前更复杂的尝试留下的遗产。我已经调整了答案。
    • @mjs1295 - 并非没有更多信息。你发送的代码是你正在运行的,还是你在简化/替换东西?您的实际数据是否包含会导致问题的缺失或不平衡块?
    猜你喜欢
    • 1970-01-01
    • 2018-09-01
    • 2021-06-04
    • 2022-01-03
    • 2020-04-15
    • 2020-04-17
    相关资源
    最近更新 更多