[英]How do I mutate a list-column to a common one leaving only the last value when there is a vector in the list?
I am trying to use purrr::map_chr
to get the last element of the vector in a list-column as the actual value in case that it exists.我正在尝试使用purrr::map_chr
来获取列表列中向量的最后一个元素作为实际值,以防它存在。
THE reproducible example:可重现的例子:
library(data.table)
library(purrr)
x <- data.table(one = c("a", "b", "c"), two = list("d", c("e","f","g"), NULL))
I want data as it is but changing my list-column to a common one with "g" as the value for x[2,2]
.我想要数据原样,但将我的列表列更改为通用的,其中 "g" 作为x[2,2]
的值。 What I've tryed:我尝试过的:
x %>% mutate(two = ifelse(is.null(.$two), map_chr(~NA_character_), map_chr(~last(.))))
The result should be the next one.结果应该是下一个。
# one two
# a d
# b g
# c NA
Thaks in advance!提前谢谢!
Here is an option.这是一个选项。 We can use if/else
instead of ifelse
here我们可以在这里使用if/else
而不是ifelse
library(dplyr)
library(tidyr)
x %>%
mutate(two = map_chr(two, ~ if(is.null(.x)) NA_character_ else last(.x)))
# one two
#1 a d
#2 b g
#3 c NA
Or replace
the NULL
elements with NA
and extract the last
或者用NA
replace
NULL
元素并提取last
x %>%
mutate(two = map_chr(two, ~ last(replace(.x, is.null(.), NA))))
I would propose this solution which is a bit cleaner.我会提出这个更清洁的解决方案。
library(tidyverse)
df <- tibble(one = c("a", "b", "c"), two = list("d", c("e","f","g"), NULL))
df %>%
mutate_at("two", replace_na, NA_character_) %>%
mutate_at("two", map_chr, last)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.