在列表的列表中删除和添加元素
Removing and adding elements in a list of lists
我有如下数据:
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")
我想做两件事:
- 删除每个列表的最后一项
- 附加字符串值
"Infinity"
和 "SUM"
正常情况下可以
x <- c(1,2,3)
x <- x[-length(x)]
x <- append(x, c("Infinity", "SUM"))
但是如果这些向量在一个列表中,它是如何工作的呢?
期望的输出:
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")
您可以使用 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
通过 purrr
包的另一个选项:
library(dplyr)
dat %>%
purrr::pmap(~c(.x)) %>%
purrr::map(~.x %>%
head(-1) %>%
append(c("Infinity", "SUM")))
将 map
与 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
我有如下数据:
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")
我想做两件事:
- 删除每个列表的最后一项
- 附加字符串值
"Infinity"
和"SUM"
正常情况下可以
x <- c(1,2,3)
x <- x[-length(x)]
x <- append(x, c("Infinity", "SUM"))
但是如果这些向量在一个列表中,它是如何工作的呢?
期望的输出:
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")
您可以使用 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
通过 purrr
包的另一个选项:
library(dplyr)
dat %>%
purrr::pmap(~c(.x)) %>%
purrr::map(~.x %>%
head(-1) %>%
append(c("Infinity", "SUM")))
将 map
与 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