简体   繁体   English

for循环浏览数据帧列表并将结果保存在新数据帧中

[英]for loop through a list of data frames and save results in new data frame

I want to fetch some values out of a list of data frames and save the results in a new data frame. 我想从数据帧列表中获取一些值,并将结果保存在新的数据帧中。 This is how my code looks: 这是我的代码的样子:

for (i in 1:length(covpatient)){

    a <- names(covpatient[i])
    b <- sum(covpatient[[i]]$cov == 0)
    c <- sum(covpatient[[i]]$cov > 0 & covpatient[[i]]$cov <= 40)
    d <- sum(covpatient[[i]]$cov > 40 & covpatient[[i]]$cov <= 100)
    e <- sum(covpatient[[i]]$cov > 100)
    summary <- c(a,b,c,d,e)

} }

So for every dataframe in the list covpatient, I want to create a summary variable which consists of 5 elements (a,b,c,d,e). 因此,对于清单耐心患者列表中的每个数据框,我想创建一个由5个元素(a,b,c,d,e)组成的摘要变量。 Then I want to make a new data.frame which stores all summary values (5 columns & i rows). 然后,我要创建一个新的data.frame,其中存储所有摘要值(5列和i行)。

Could someone give me a hand? 有人可以帮我吗?

One way is to use lapply with rbind and then call as.data.frame . 一种方法是对rbind使用lapply ,然后调用as.data.frame Since there is no data to play with, I'll give the general idea. 由于没有数据可玩,因此我将给出一个总体思路。

o <- lapply(1:length(covpatient), function(i) {
    a <- names(covpatient[i])
    b <- sum(covpatient[[i]]$cov == 0)
    c <- sum(covpatient[[i]]$cov > 0 & covpatient[[i]]$cov <= 40)
    d <- sum(covpatient[[i]]$cov > 40 & covpatient[[i]]$cov <= 100)
    e <- sum(covpatient[[i]]$cov > 100)
    c(a,b,c,d,e)
})
out <- as.data.frame(do.call(rbind, o))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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