Home > Back-end >  Add a column item, as the first element of a list in another column
Add a column item, as the first element of a list in another column

Time:04-24

I have data as follows:

dat <- structure(list(`[0,25)` = c(5L, 0L), freq = list(c(43, 20, 38, 
27, 44, 177), c(5, 3, 12, 53, 73))), class = c("rowwise_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L), groups = structure(list(
    .rows = structure(list(1L, 2L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame")))

enter image description here

I would simply like to add the item in column [0,25) (as the first item) to the list in column freq.

Desired output

dat <- structure(list(`[0,25)` = c(5L, 0L), freq = list(c(5, 43, 20, 38, 
27, 44, 177), c(0, 5, 3, 12, 53, 73))), class = c("rowwise_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L), groups = structure(list(
    .rows = structure(list(1L, 2L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame")))

enter image description here

I tried:

dat$freq <- lapply(dat$freq, \(x){
  x <- append(dat$`[0,25)`, x)
  x
})

But that appends the whole vector. How should I do this?

CodePudding user response:

concatenating.

transform(dat, freq=Map('c', dat[[1]], dat[[2]]))
#   X.0.25.                       freq
# 1       5 5, 43, 20, 38, 27, 44, 177
# 2       0        0, 5, 3, 12, 53, 73
  • Related