通过使用is_empty(),用na替换字符(0)的列表元素
我有一个dataframe(my_df
),其中一行中,带有cartare(0)
的列表。
我想通过使用rlang的is_empty()
替换na_character
。我知道通过使用例如长度(x)== 0有解决方法,但是我试图理解为什么我使用iS_empty()
的方法不起作用。感谢任何提示。
library(tidyverse)
my_df <- data.frame(
stringsAsFactors = FALSE,
type = c("house", "tent", "treehouse, mainhouse")
) %>%
mutate(house=str_extract_all(type, regex("house")))
my_df
#> type house
#> 1 house house
#> 2 tent
#> 3 treehouse, mainhouse house, house
class(my_df$house)
#> [1] "list"
my_df %>%
mutate(house_mod=modify_if(house,
.p = is_empty(house),
.f = NA_character_))
#> Error in `mutate()`:
#> ! Problem while computing `house_mod = modify_if(house, .p =
#> is_empty(house), .f = NA_character_)`.
#> Caused by error in `probe()`:
#> ! length(.p) == length(.x) is not TRUE
my_df <- my_df %>%
mutate(house_empty=map(house, ~is_empty(.)))
my_df
#> type house house_empty
#> 1 house house FALSE
#> 2 tent TRUE
#> 3 treehouse, mainhouse house, house FALSE
my_df %>%
mutate(house_mod=modify_if(house,
.p = house_empty==T,
.f = NA_character_))
#> Error in `mutate()`:
#> ! Problem while computing `house_mod = modify_if(house, .p = house_empty
#> == T, .f = NA_character_)`.
#> ✖ `house_mod` must be size 3 or 1, not 2.
由
I have a dataframe (my_df
) with a list called 'house' with character(0)
in one row.
I would like to replace this value with NA_character
by using rlang's is_empty()
. I am aware that there are workarounds by using e.g. length(x)==0, but I am trying to understand why my approach with is_empty()
does not work. Grateful for any hint.
library(tidyverse)
my_df <- data.frame(
stringsAsFactors = FALSE,
type = c("house", "tent", "treehouse, mainhouse")
) %>%
mutate(house=str_extract_all(type, regex("house")))
my_df
#> type house
#> 1 house house
#> 2 tent
#> 3 treehouse, mainhouse house, house
class(my_df$house)
#> [1] "list"
my_df %>%
mutate(house_mod=modify_if(house,
.p = is_empty(house),
.f = NA_character_))
#> Error in `mutate()`:
#> ! Problem while computing `house_mod = modify_if(house, .p =
#> is_empty(house), .f = NA_character_)`.
#> Caused by error in `probe()`:
#> ! length(.p) == length(.x) is not TRUE
my_df <- my_df %>%
mutate(house_empty=map(house, ~is_empty(.)))
my_df
#> type house house_empty
#> 1 house house FALSE
#> 2 tent TRUE
#> 3 treehouse, mainhouse house, house FALSE
my_df %>%
mutate(house_mod=modify_if(house,
.p = house_empty==T,
.f = NA_character_))
#> Error in `mutate()`:
#> ! Problem while computing `house_mod = modify_if(house, .p = house_empty
#> == T, .f = NA_character_)`.
#> ✖ `house_mod` must be size 3 or 1, not 2.
Created on 2022-05-23 by the reprex package (v2.0.1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.f
参数应采用一个函数,但是您刚刚通过na_character _
。尝试〜na_character _
:The
.f
argument should take a function, but you have just passedNA_character_
directly. Try~NA_character_
: