基于没有长数据的另一个数据帧创建NA

时间:2020-07-03 19:41:30

标签: r dplyr

我有一个tibble,带有显式的“ id”和我需要转换为NA的别名。无论如何,我可以不用创建df较长数据集就可以创建NA的问题?我考虑过使用新的rows_update函数,但是我不确定这是否正确,因为我只希望某些列为NA。

library(dplyr)

to_na <- tribble(~x, ~col,
        1, "z",
        3, "y"
)

df <- tibble(x = c(1,2,3), 
       y = c(1,1,1), 
       z = c(2,2,2)) 

# desired output:
#> # A tibble: 3 x 3
#>       x     y     z
#>   <dbl> <dbl> <dbl>
#> 1     1     1    NA
#> 2     2     1     2
#> 3     3    NA     2

reprex package(v0.3.0)于2020-07-03创建

2 个答案:

答案 0 :(得分:1)

这绝对不是最优雅的解决方案,但是它可以获取您想要的输出。

library(dplyr)
library(purrr)

to_na <- tribble(~x, ~col,
                 1, "z",
                 3, "y"
)

df <- tibble(x = c(1,2,3), 
             y = c(1,1,1), 
             z = c(2,2,2))

map2(to_na$x, to_na$col, #Pass through these two objects in parallel
     function(xval_to_missing, col) df %>% #Two objects above matched by position here.
                          mutate_at(col, #mutate_at the specified cols
                                    ~if_else(x == xval_to_missing, NA_real_, .) #if x == xval_to_missing, make NA, else keep as is.
                                    ) %>% 
                          select(x, col) #keep x and the modified column.
     ) %>% #end of map2
reduce(left_join, by = "x") %>% #merge within the above list, by x.
relocate(x, y, z) #Keep your ordering

输出:

# A tibble: 3 x 3
      x     y     z
  <dbl> <dbl> <dbl>
1     1     1    NA
2     2     1     2
3     3    NA     2

答案 1 :(得分:0)

我们可以使用row/column索引将值分配给NA中的base R

df <- as.data.frame(df)
df[cbind(to_na$x, match(to_na$col, names(df)))] <- NA
df
#  x  y  z
#1 1  1 NA
#2 2  1  2
#3 3 NA  2

如果我们要使用rows_update

library(dplyr)
library(tidyr)
library(purrr)
lst1 <- to_na %>%
            mutate(new = NA_real_) %>%
            split(seq_len(nrow(.))) %>%
            map(~ .x %>% 
               pivot_wider(names_from = col, values_from = new))
for(i in seq_along(lst1)) df <- rows_update(df, lst1[[i]])

df
# A tibble: 3 x 3
#       x     y     z
#   <dbl> <dbl> <dbl>
#1     1     1    NA
#2     2     1     2
#3     3    NA     2