0
votes

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)

1

1 Answers

0
votes

The .f argument should take a function, but you have just passed NA_character_ directly. Try ~NA_character_ :

my_df %>% 
     mutate(house_mod=modify_if(house,
                                .p = is_empty,
                                .f = ~NA_character_))
#>                   type        house    house_mod
#> 1                house        house        house
#> 2                 tent                        NA
#> 3 treehouse, mainhouse house, house house, house