![](/img/trans.png)
[英]What arguments for self-defined functions for use on list of data frames in R
[英]Apply self-defined function on list of data frames in R
這是我之前的問題的后續: R 中的代碼以有條件地減去數據幀中的列
我現在想將給定的解決方案應用於我以前的問題
cols <- grep('^\\d+$', names(df), value = TRUE)
new_cols <- paste0(cols, '_corrected')
df[new_cols] <- df[cols] - df[paste0('Background_', cols)]
df[c("Wavelength", new_cols)]
到列表中的每個數據框。 我導入 excel 文件的所有工作表,以便使用此代碼將每個工作表都變成列表中的一個數據框(由Read all worksheets in an Excel workbook into an ZE1E1D3D40573127E9EE0480CAF1 提供)
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
}
mysheets <- read_excel_allsheets(file.choose())
如何將第一個代碼框應用於我的數據框列表?
我想從這樣的事情中得到:
df_1 <- structure(list(Wavelength = 300:301, Background_1 = c(5L, 3L),
`1` = c(11L, 12L), Background_2 = c(4L, 5L), `2` = c(12L, 10L)),
class = "data.frame", row.names = c(NA, -2L))
df_2 <- structure(list(Wavelength = 300:301, Background_1 = c(6L, 4L),
`1` = c(10L, 13L), Background_2 = c(5L, 6L), `2` = c(11L, 11L),
Background_3 = c(4L, 6L), `3` = c(13L, 13L)),
class = "data.frame", row.names = c(NA, -2L))
df_list <- list(df_1, df_2)
對於這樣的事情:
df_1_corrected <- structure(list(Wavelength = 300:301, `1_corrected` = c(6L, 9L),
`2_corrected` = c(8L, 5L)),
class = "data.frame", row.names = c(NA, -2L))
df_2_corrected <- structure(list(Wavelength =300:301, `1_corrected` = c(4L, 9L),
`2_corrected` = c(6L, 5L),
`3_corrected` = c(9L, 7L)),
class = "data.frame", row.names = c(NA, -2L))
df_corrected_list <- list(df_1_corrected, df_2_corrected)
實際數據摘錄
Wavelength Background 1 1 Background 2 2 Background 3 3
300 273290.0 337670.0 276740.0 397530 288500.0 367480.0
301 299126.7 375143.3 299273.3 432250 310313.3 394796.7
我已經閱讀了lapply
function 將用於此,但我以前從未使用過它,因為我是 R 的初學者。 非常感謝您的幫助!
您可以將代碼放入 function 並使用 lapply 將其應用於列表中的每個lapply
:
subtract_values <- function(df) {
cols <- grep('^\\d+$', names(df), value = TRUE)
new_cols <- paste0(cols, '_corrected')
df[new_cols] <- df[cols] - df[paste0('Background ', cols)]
df[c("Wavelength", new_cols)]
}
lapply(df_list, subtract_values)
#[[1]]
# Wavelength 1_corrected 2_corrected
#1 300 6 8
#2 301 9 5
#[[2]]
# Wavelength 1_corrected 2_corrected 3_corrected
#1 300 4 6 9
#2 301 9 5 7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.