简体   繁体   English

列表中的双循环

[英]Double loop in a list r

Here is a simplification of my problem using simulated data. 这是使用模拟数据简化我的问题的方法。 I want to perform a double loop over the elements of a list to get some summary statistics. 我想对列表的元素执行双重循环以获取一些摘要统计信息。 Here is a simplification of my data structure and approchimation: 这是我的数据结构和近似的简化:

x1 <- runif(10, 5.0, 7.5)
x2 <- runif(10,3,7)
x3 <- runif(10,1,9)
x4 <- rep(1:2, c(6,4))
bag<-data.frame(cbind(x1,x2,x3,x4))
x1 <- runif(10, 5.0, 7.5)
x2 <- runif(10,3,7)
x3 <- runif(10,1,9)
x4 <- rep(1:2, c(6,4))
zul<-data.frame(cbind(x1,x2,x3,x4))
x1 <- runif(10, 5.0, 7.5)
x2 <- runif(10,3,7)
x3 <- runif(10,1,9)
x4 <- rep(1:2, c(6,4))
lwk<-data.frame(cbind(x1,x2,x3,x4))
x1 <- runif(10, 5.0, 7.5)
x2 <- runif(10,3,7)
x3 <- runif(10,1,9)
x4 <- rep(1:2, c(6,4))
job<-data.frame(cbind(x1,x2,x3,x4))
lts <- list(bag,zul,lwk,job)
 for (i in 1:4){
colnames(lts[[i]])=c("val1","val2","val3","class")
}

Now I can get, for example, means of value1 of each of the elements of the list: 现在,例如,我可以获得列表中每个元素的value1平均值:

lst.mean.c1<-list()
for (i in 1:4){
lst.mean.c1[[i]]<-mean(lts[[i]]$val1[lts[[i]]$class==1])
}

But want I want is to get a list with all the means for variables value1, value2, value3. 但我想要获得的列表包含变量value1,value2,value3的所有方法。 I tried to do it like this: 我试图这样做:

num<-seq(1:3)
idc<-gsub(".val","",gsub(".val","",num))
lts.mean.val<-list()
for (j in 1:4){
    for ( i in idc){
        lts.mean.val[[i]]<-mean(lts[[j]]$val[[i]][lts[[j]]$class==1]) 
    } 
}

I did not have any success. 我没有任何成功。 Could you help me 你可以帮帮我吗

For example using colMeans as mentioned in the comment: 例如,使用colMeans中提到的colMeans

 lapply(lts,
  function(x) colMeans(x[,grep("val",names(x))]))

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

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