简体   繁体   中英

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.

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] . 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

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

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)

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