簡體   English   中英

R:在lapply中的函數中傳遞相應數據幀的索引(來自數據幀列表)

[英]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中相應數據幀的索引,以便各個行可以具有各自的dmvmethod名稱。 怎么做?

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.

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