Modify and recreate a list of data.frame in R

守給你的承諾、 提交于 2019-12-06 13:57:34

问题


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)


来源:https://stackoverflow.com/questions/57118322/modify-and-recreate-a-list-of-data-frame-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!