[英]What arguments for self-defined functions for use on list of data frames in R
所以我一直在研究一個自動進行一些數據分析的腳本,而不是讓用戶在 excel 中手動完成所有事情。 我希望 R 將給定 Excel 文件的所有工作表作為數據幀放在列表中,並使用自定義函數對這些數據幀中的每一個執行一些操作。 到目前為止,這是我的代碼:
###Install required packages if necessary
if(!require("tidyverse")) install.packages("tidyverse")
if(!require("fs")) install.packages("fs")
if(!require("readxl")) install.packages("readxl")
if(!require("matrixStats")) iinstall.packages("matrixStats")
###Load required packages
library(tidyverse)
library(fs)
library(readxl)
library(matrixStats)
###Define functions
#Import all sheets into a list from an Excel file
read_excel_allsheets <- function(filename, tibble = FALSE) {
sheets <- readxl::excel_sheets(filename)
x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
if(!tibble) x <- lapply(x, as.data.frame)
names(x) <- sheets
x
}
#Subtract "Background" column from corresponding measurement column
correct_background <- function(df) {
cols <- grep('^\\d+$', names(df), value = TRUE)
new_cols <- paste0(cols, '_corrected')
df[new_cols] <- df[cols] - df[paste0('Background ', cols)]
}
#Calculate means and standard deviations and drop "_corrected" columns
mean_SD <- function(df) {
df$mean <- rowMeans(select(df, contains("_corrected")))
df$SD <- rowSds(as.matrix(select(df, contains("_corrected"))))
df <- subset(df, select = c("Wavelength", "mean", "SD"))
}
###Apply functions
#Load all Excel sheets of chosen file into a list of data frames
mysheets <- read_excel_allsheets(file.choose())
#Apply background correction on every data frame in the list
lapply(mysheets, correct_background)
#Apply function to calculate mean and SD
lapply(mysheets, mean_SD)
現在它失敗的地方是###Apply functions
部分。 第一個 function,一個加載 Excel 工作表的工作正常,但我認為我需要為第二個和第三個 function 定義一個參數,無論它們的名稱如何,它們都應該在列表中的任何框架上工作。 是否有默認方法來引用 R 列表中的每個數據幀? 還是我需要手動定義? 非常感謝幫助!
您需要保存lapply
操作的結果。 將您的lapply
語句更改為以下內容。
#Apply background correction on every data frame in the list
mysheets <- lapply(mysheets, correct_background)
#Apply function to calculate mean and SD
mysheets <- lapply(mysheets, mean_SD)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.