我的資料如下:
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")
uj5u.com熱心網友回復:
您可以使用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
uj5u.com熱心網友回復:
與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
uj5u.com熱心網友回復:
purrr通過軟體包的另一種選擇:
library(dplyr)
dat %>%
purrr::pmap(~c(.x)) %>%
purrr::map(~.x %>%
head(-1) %>%
append(c("Infinity", "SUM")))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/462274.html
下一篇:展平深度嵌套的資料框串列
