Home > front end >  How to add a list name as a column at a nested list data.frame in r
How to add a list name as a column at a nested list data.frame in r

Time:06-06

I am trying to add the list name that wraps the sublist with a dataset as a column of the last one to allow me call the rbind afterwards and join all the datasets. In other words, to join the datasets I need to keep the original list name for reference. I acomplished it with a for, but I wonder if I could use the purrr methods or apply functions instead because my data is far more complex than this below. To ilustrate what I mean, I share a simple example:

x1 <- data.frame(a = 1:3, b = letters[1:3])
x2 <- data.frame(a = 4:6, b = letters[4:6])
y1 <- data.frame(a = 10:15, b = letters[10:15])
y2 <- data.frame(a = 13:17, b = letters[13:17])
l1 <- list(x1, y1)
l2 <- list(x2, y2)
l <- list(l1, l2)
nm <- c("list1", "list2")
names(l) <- nm
lmod <- l
for (i in 1:length(lengths(l))) { 
  for(j in 1:length(l[[i]])) { 
    lmod[[i]][[j]]$nm = names(l[i])
    }
  }

Using lapply I tryied something like:

lmod <- lapply(l, function(x) {
  x[[1]] <- names(x)
  x[[2]] <- names(x)
  return(x)
})

But it did not work at all.

Does anyone has a clue on this one?

CodePudding user response:

Map(lapply, l, list(cbind), nm=names(l))

This can also be written as:

Map(\(x, y)lapply(x, cbind, nm = y),l, names(l))


all.equal(lmod,  Map(lapply, l, list(cbind), nm=names(l)))
[1] TRUE
  • Related