简体   繁体   English

当列表中有一个向量时,如何将列表列变异为一个普通的列,只留下最后一个值?

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

相关问题 使用 case_when,如何改变嵌套向量的新列表列? - Using case_when, how to mutate a new list-column that nests a vector within? 如何在列表列和外部向量之间的 data.table 中进行行匹配? - How to do rowwise matching in data.table between list-column and external vector? 如何创建一个列表列,它是 R 中另一个列表列的子集? - How can I make a list-column that is a subset of another list-column in R? 如何“传播”列表列? - how to “spread” a list-column? 为数据框中的一列创建列表列 - Creates list-column for one column in dataframe 在mutate中使用purrr :: pmap创建list-column - Using purrr::pmap within mutate to create list-column 如何通过将字符串转换为环境中可用的同名函数来改变包含函数的列表列? - How to mutate a list-column that holds functions by converting strings to functions with the same name that are available in the environment? 如何使用 purrr::map() 改变列表列以存储通过 recipe() 创建的“recipe”object? - How to mutate a list-column using purrr::map() to store a "recipe" object created via recipe()? 如何使用huxtable()在小标题中使用回归模型的打印列表列 - How do I use print list-column of regression models in a tibble using huxtable() 如何将ggplots的列表列打印为pdf? - how to print a list-column of ggplots to pdf?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM