Home > front end >  add vector/list to element of r dataframe
add vector/list to element of r dataframe

Time:07-06

I have a dataframe, and I would like to add a new column whose elements are themselves vectors (or lists). The vectors/lists may might not be expressible in closed form. I tried the following but received an error

> mydf = data.frame(a=1:3)
> mydf$new <-  vector('list', nrow(mydf))
> for(i in seq_len(nrow(mydf))) {
    mydf$new[i] <- rep(i, ceiling(10 * runif(1)))
  }
Warning messages:
1: In mydf$new[i] <- rep(i, ceiling(10 * runif(1))) :
  number of items to replace is not a multiple of replacement length
2: In mydf$new[i] <- rep(i, ceiling(10 * runif(1))) :
  number of items to replace is not a multiple of replacement length
3: In mydf$new[i] <- rep(i, ceiling(10 * runif(1))) :
  number of items to replace is not a multiple of replacement length

What is the correct way?


Old question: how to populate a new column with vs

v1 = c(1,2,3)
v2 = c(4,5)
v3 = c(6,7,8,9,10)
vs = list(v1, v2, v3)
mydf = data.frame(a=1:3)
for (i in 1:3){
  v = rep(i, ceil(10 * runif(1)))
  mydf[i, "new"] = vs[i]
}

CodePudding user response:

If we want to do this in a for loop, wrap the rep output in a list

mydf$new <- vector('list', nrow(mydf))
for(i in seq_len(nrow(mydf))) {
   mydf$new[i] <- list(rep(i, ceiling(10 * runif(1))))
 }

-output

> mydf
  a                 new
1 1             1, 1, 1
2 2          2, 2, 2, 2
3 3 3, 3, 3, 3, 3, 3, 3

CodePudding user response:

Another possible solution:

library(tidyverse)

mydf %>% 
  mutate(new = imap(a, ~ rep(.y, ceiling(10 * runif(1)))))

#>   a                          new
#> 1 1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
#> 2 2             2, 2, 2, 2, 2, 2
#> 3 3       3, 3, 3, 3, 3, 3, 3, 3
  • Related