I have a list of 9 data frames list_dataframes
read from files and a function func_modification
to modify them. I would like to pass the value of pos
the index of the corresponding data frame in list, so that individual rows can have their respective dmv
and method
names. How to do that?
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
You can try Map
to change the corresponding dataframes with each element of 'pos'
Map(func_modification, list_dataframes, pos= 1:3)
Or using lapply
lapply(seq_along(list_dataframes), function(i)
func_modification(list_dataframes[[i]], pos=i))
where func_modification
is
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)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.