[英]R: Passing the index of the corresponding data frame (from a list of data frames) in a function within lapply
我有一個從文件中讀取的9個數據幀list_dataframes
的列表,以及一個函數func_modification
來修改它們。 我想將pos
的值傳遞給list中相應數據幀的索引,以便各個行可以具有各自的dmv
和method
名稱。 怎么做?
dmv <- c(rep("MC", 3), rep("MSM", 3), rep("Random", 3))
method <- rep(c("COM-0.5", "IDT", "LB"), 3)
func_modification <- function(d, pos) {
d[,1] <- d[,1]/3600
d[,3] <- NA
d[,3] <- dmv[pos]
d[,4] <- method[pos]
}
list_df <- list()
list_df <- lapply(list_dataframes, func_modification, pos=3) // Works
list_df <- lapply(list_dataframes, func_modification, pos=1:9) // Showing error
您可以嘗試使用Map
更改“ pos”的每個元素的相應數據框
Map(func_modification, list_dataframes, pos= 1:3)
或使用lapply
lapply(seq_along(list_dataframes), function(i)
func_modification(list_dataframes[[i]], pos=i))
func_modification
在哪里
func_modification <- function(d, pos) {
d[,1] <- d[,1]/3600
d[,3] <- NA #not sure if this needed
d[,3] <- dmv[pos]
d[,4] <- method[pos]
d #return the data
}
set.seed(24)
list_dataframes <- lapply(1:3, function(i)
as.data.frame(matrix(sample(1:10, 5*20, replace=TRUE), ncol=5)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.