将函数应用于 R 中的列表列表的最佳方法是什么?特别是如果内部变量都被称为同一事物

What is the best way to apply a function to a list of lists in R? specifically if the internal variables are all called the same thing

嗨,我是 R 的新手,非常感谢对此的任何帮助。

我搜索过类似的问题,但不幸的是我不太理解给出的解决方案。

我的问题:

我有大约 60 excel 张重复测试数据,我想分析和比较这些数据。这些都具有相似的结构和 variable/column 个名称,但每个数据点的数量不同。 我已将它们作为列表列表加载到 R 中,并且我想在每个原始数据集位于列表列表中后对其执行一系列操作。这些操作使用相同的变量名称等是相同的,但应用于不同的数据集。

举个例子,我想根据数据计算一些东西,然后将结果作为新变量添加到嵌套列表中。

我的情况的简化版本是这样的。

###set up###

specimen1=list("Stress"=50:100,
"Strain"=5:55) #represents my excel sheet imports
specimen2=list("Stress"=65:115,
"Strain"=6.5:56.5) #simplifed for brevity

specimen3=list("Stress"=42:92,"Strain"=4.2:54.2)

rate1=list(specimen1,specimen2,specimen3) #my list of lists

names(rate1)<-c("specimen 1","specimen 2","specimen 3") #set the names
####performing calculation and adding to the list entry###

#now i want to perform a calculation on each specimen and then add the result to that specimen
#I suspect the solution lies with the lapply family something like this?

example_function<-function(Stress,Strain){

E=Stress/Strain #performs calculation
#but doesn't add the result to the list?

rate1$specimen$E=E #something like this to add to the original data set?
#but I don't understand how to change the indexing with out using a for loop

}


lapply(rate1,example_function)

#########

对列表列表的每个元素执行函数然后将变量添加到所有这些列表组件的最佳方法是什么?

我怀疑这个问题的解决方案很简单?

如果您在 lists 中不受限制,您可以绑定所有列表并使用 dplyr

以生成的 data.frame 格式执行此操作
library(dplyr)
bind_rows(rate1, .id="specimen") %>% 
 mutate(E = Stress/Strain)

产生

# A tibble: 153 x 4
   specimen   Stress Strain     E
   <chr>       <int>  <dbl> <dbl>
 1 specimen 1     50      5 10   
 2 specimen 1     51      6  8.5 
 3 specimen 1     52      7  7.43
 4 specimen 1     53      8  6.62
...

使用 data.frames 通常是 R 中最直接的处理方式。

如果您想继续使用 lists,因为您必须创建一个新列,最好使用 for 循环而不是 lapply。这就是您使用循环解决特定问题的方法。

# this will add the column E to each element of the list rate1
for(i in 1:length(rate1)) {
  rate1[[i]]$E <- rate1[[i]]$Stress/rate1[[i]]$Strain  
}

这是带有 lapply 的版本,您可以在 function(li).

list 调用中继续添加列
modified_rate1 <- 
lapply(rate1, function(li) 
  list(
    Stress = li$Stress,
    Strain = li$Strain,
    E = li$Stress/li$Strain
  )
)

我认为在 data.frame 中这样做是可行的方法,但您应该看看什么对您的其他许多目的更好