用于 R 中数据帧列表的自定义函数的参数是什么

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 部分。第一个函数,加载 Excel 工作表的函数工作正常,但我想我需要为第二个和第三个函数定义一个参数,告诉他们他们应该处理列表中的任何数据框,无论其名称如何.是否有默认方法来引用 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)