簡體   English   中英

如何使用lapply而不是for循環對R中的數據幀列表執行計算

[英]how to use lapply instead of a for loop, to perform a calculation on a list of dataframes in R

我有30個數據框的列表。

我想創建一個向量,該向量包含數據幀列表中所有30個數據幀中列之一的第n個元素的標准偏差。 我認為我沒有清楚地說明這一點。 但是我的for循環的代碼應該很清楚。

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,但是我不知道該怎么做。 我嘗試了以下方法:

results2738 <- lapply( FFT2738_data , function(x) {sd(x) } )

但它導致以下錯誤:

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

如果有人可以建議我調查的資源,我將不勝感激。

像這樣:

FFT233_sd <- sapply(1:431999, function(i) {
  values <- sapply(1:length(FFT233_data), function(j) {
    FFT233_data[[j]][i,6]
  })
  sd(values)
}

嘗試這個

可重現的示例,mtcar列表(重復10次)

library(purrr)
L <- map(1:10, ~mtcars)

您需要purrr:map

library(purrr)
sixthcol <- Reduce("cbind", map(L, ~.x[,6]))
ans <- apply(sixthcol, 1, sd)

產量

sixthcol <- Reduce("cbind", map(L, ~.x[,6]))

 [1,] 2.620 2.620 2.620 2.620 2.620 2.620 2.620 2.620 2.620 2.620
 [2,] 2.875 2.875 2.875 2.875 2.875 2.875 2.875 2.875 2.875 2.875
 [3,] 2.320 2.320 2.320 2.320 2.320 2.320 2.320 2.320 2.320 2.320
 [4,] 3.215 3.215 3.215 3.215 3.215 3.215 3.215 3.215 3.215 3.215
 [5,] 3.440 3.440 3.440 3.440 3.440 3.440 3.440 3.440 3.440 3.440
 [6,] 3.460 3.460 3.460 3.460 3.460 3.460 3.460 3.460 3.460 3.460
 [7,] 3.570 3.570 3.570 3.570 3.570 3.570 3.570 3.570 3.570 3.570
 [8,] 3.190 3.190 3.190 3.190 3.190 3.190 3.190 3.190 3.190 3.190
 # etc

ans <- apply(sixthcol, 1, sd)

# 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM