Home > front end >  Putting back a missing column from a data.frame into a list of dta.frames
Putting back a missing column from a data.frame into a list of dta.frames

Time:11-06

My LIST of data.frames below is made from my data. However, this LIST is missing the scale column which is available in the original data.

I was wondering how to put back the missing scale column into LIST to achive my DESIRED_LIST?

Reproducible data and code are below.

m3="
scale study   outcome time
2       1       1      0
2       1       2      0
1       2       1      0
1       2       1      1
2       3       1      0
2       3       1      1
1       4       1      0
1       4       2      0"
data <- read.table(text = m3, h=T)

LITS <-         list(data.frame(study=c(3,3)    ,outcome=c(1,1)    ,time=0:1),
                     data.frame(study=c(1,1)    ,outcome=c(1,2)    ,time=c(0,0)),
                     data.frame(study=c(2,2,4,4),outcome=c(1,1,1,2),time=c(0,1,0,0)))

DESIRED_LIST <- list(data.frame(scale=c(2,2)    ,study=c(3,3)    ,outcome=c(1,1)    ,time=0:1),
                     data.frame(scale=c(2,2)    ,study=c(1,1)    ,outcome=c(1,2)    ,time=c(0,0)),
                     data.frame(scale=c(1,1,1,1),study=c(2,2,4,4),outcome=c(1,1,1,2),time=c(0,1,0,0)))

CodePudding user response:

In base R, you could do:

lapply(LITS, \(x)merge(x, data)[names(data)])
  • Related