简体   繁体   中英

Removing and adding elements in a list of lists

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")

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

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

Another option via the purrr package:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM