簡體   English   中英

將 function 應用於 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 表,里面充滿了我想要分析和比較的重復測試數據。 這些都具有相似的結構和變量/列名稱,但每個數據點的數量不同。 我已將這些作為列表列表加載到 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)

#########

對列表列表的每個元素執行 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的方法,但您應該看看什么對您的其他許多目的更好

暫無
暫無

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

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