Modify and recreate a list of data.frame in R

2020-07-30 04:06发布

问题:

I have a list of data.frames called m (see HERE). Column r in these data.frames is all NA.

But later on, I have computed some of these rs and stored them as a list called L.

I'm wondering how to achieve the following?:

(1) If any list entry in L (i.e., L[[1]], L[[2]], ...), starts with a number BUT right after it is NA, replace NA with that number.

(2) Put back all new rs (stored in L) in column r, in the original list of data.frames m.

D <- read.csv("https://raw.githubusercontent.com/izeh/m/master/g.csv", h = T) ## Data


m <- split(D, D$study.name) ;  m[[1]] <- NULL  ## original list of data.frame    
                                               ## To be finally recreated.


 L <- list(Bit.KnoA = rep(NA, 8), Bit.KnoB = rep(NA, 12), ChandlerA = c(.5, .5), 
Mubarak = c(.6, NA, .5, NA, .5, NA, .8, NA, .5,NA,.9,NA), SheenA = rep(NA, 6),
Shin.Ellis = rep(NA, 6), Sun = rep(NA, 6), Trus.Hsu = rep(NA, 2))


lapply(L, transform, r = zoo::na.locf0(r)) ## To achieve (1), but Not working !


###### NOW, put back L in the new list of data.frame like `m` above? ######

回答1:

If the intention is to replace the 'r' column in the list of data.frame in 'm' with the corresponding 'L' list of vectors applied with na.locf0, then

library(zoo)
m1 <- Map(function(x, y) transform(x, r = na.locf0(y)), m, L)