如何使用lapply而不是for循环对R中的数据帧列表执行计算 [英] how to use lapply instead of a for loop, to perform a calculation on a list of dataframes in R
问题描述
我有30个数据帧的列表.
I have a list of 30 dataframes.
我想创建一个向量,该向量包含数据帧列表中所有30个数据帧中列之一的第n个元素的标准偏差.我认为我没有清楚地解释这一点.但是我的for循环的代码应该很清楚.
I want to create a vector that contains the standard deviation of the nth element of one of the columns, across all 30 data frames in the list of dataframes. I don't think I've explained that clearly. But the code for my for loop should make it clear.
FFT233_sd <- list()
for (i in 1:431999) {FFT233_sd[[i]] <- sd(c(FFT233_data[[1]][i,6], FFT233_data[[2]][i,6], FFT233_data[[3]][i,6], FFT233_data[[4]][i,6], FFT233_data[[5]][i,6], FFT233_data[[6]][i,6], FFT233_data[[7]][i,6], FFT233_data[[8]][i,6], FFT233_data[[9]][i,6], FFT233_data[[10]][i,6], FFT233_data[[11]][i,6], FFT233_data[[12]][i,6], FFT233_data[[13]][i,6], FFT233_data[[14]][i,6], FFT233_data[[15]][i,6], FFT233_data[[16]][i,6], FFT233_data[[17]][i,6], FFT233_data[[18]][i,6], FFT233_data[[19]][i,6], FFT233_data[[20]][i,6], FFT233_data[[21]][i,6], FFT233_data[[22]][i,6], FFT233_data[[23]][i,6], FFT233_data[[24]][i,6], FFT233_data[[25]][i,6], FFT233_data[[26]][i,6], FFT233_data[[27]][i,6], FFT233_data[[28]][i,6], FFT233_data[[29]][i,6], FFT233_data[[30]][i,6]))}
该for循环有效,但是显然很慢.有人告诉我应该使用lapply,但是我不知道该怎么做.我尝试了以下方法:
That for loop works, but is obviously quite slow. I have been told I should use lapply, but i do not understand how to do that. I have tried the following:
results2738 <- lapply( FFT2738_data , function(x) {sd(x) } )
但是它导致了以下错误:
but it has resulted in teh following errror:
Show Traceback
Rerun with Debug
Error in is.data.frame(x) :
(list) object cannot be coerced to type 'double' In addition: Warning message:
In mean.default(x) : argument is not numeric or logical: returning NA
如果有人可以建议我调查的资源,我将不胜感激.
If anyone can suggest a resource for me to investigate, i would be greatful.
推荐答案
类似以下内容:
FFT233_sd <- sapply(1:431999, function(i) {
values <- sapply(1:length(FFT233_data), function(j) {
FFT233_data[[j]][i,6]
})
sd(values)
}
这篇关于如何使用lapply而不是for循环对R中的数据帧列表执行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!