简体   繁体   English

在列表的列表中删除和添加元素

[英]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" Append 字符串值"Infinity""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:所需的 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 :您可以使用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 mutatemapmutate一起使用

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:通过purrr package 的另一种选择:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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