Home > database >  Removing and adding elements in a list of lists
Removing and adding elements in a list of lists

Time:04-22

I have data as follows:

dat <- structure(
  list( 
  freq = list(a= c(5, 38, 43, 27, 44, 20, 177), b=c(3, 5, 12, 53, 73))), 
  row.names = c(NA, -2L), class = "data.frame")

I would like to do two things:

  1. Remove the last item of each list
  2. Append the string values "Infinity" and "SUM"

Normally one could do

x <- c(1,2,3)
x <- x[-length(x)]
x <- append(x, c("Infinity", "SUM"))

But how does that work if these vectors are in a list?

Desired output:

dat_out <- structure(
  list( 
  freq = list(a= c(5, 38, 43, 27, 44, 20, "Infinity", "SUM"), b=c(3, 5, 12, 53, "Infinity", "SUM"))), 
  row.names = c(NA, -2L), class = "data.frame")

CodePudding user response:

You can use lapply:

dat$freq <- lapply(dat$freq, \(x){
  x <- x[-length(x)]
  x <- append(x, c("Infinity", "SUM"))
  x
})`

#                                   freq
# 1 5, 38, 43, 27, 44, 20, Infinity, SUM
# 2          3, 5, 12, 53, Infinity, SUM

CodePudding user response:

Using map with mutate

library(dplyr)
library(purrr)
dat %>% 
  mutate(freq = map(freq, ~ c(.x[-n()], "Infinity", "SUM")))
                                   freq
1 5, 43, 27, 44, 20, 177, Infinity, SUM
2          3, 12, 53, 73, Infinity, SUM

CodePudding user response:

Another option via the purrr package:

library(dplyr)      
dat %>%
  purrr::pmap(~c(.x)) %>%
  purrr::map(~.x %>% 
               head(-1) %>% 
               append(c("Infinity", "SUM"))) 
  • Related