使用 dplyr 的 transmute_all 用列名替换列值

jus*_*ess 7 r dplyr

数据集包含许多包含 NA 或 1 值的列,有点像这样:

> data_frame(a = c(NA, 1, NA, 1, 1), b=c(1, NA, 1, 1, NA))
# A tibble: 5 x 2
      a     b
  <dbl> <dbl>
1 NA     1.00
2  1.00 NA   
3 NA     1.00
4  1.00  1.00
5  1.00 NA  
Run Code Online (Sandbox Code Playgroud)

所需的输出:用列名作为字符串替换所有 1 个值,

> data_frame(a = c(NA, 'a', NA, 'a', 'a'), b=c('b', NA, 'b', 'b', NA))
# A tibble: 5 x 2
  a     b    
  <chr> <chr>
1 <NA>  b    
2 a     <NA> 
3 <NA>  b    
4 a     b    
5 a     <NA> 
Run Code Online (Sandbox Code Playgroud)

这是我在 transmute_all 中使用匿名函数的尝试:

> data_frame(a = c(NA, 1, NA, 1, 1), b=c(1, NA, 1, 1, NA)) %>%
+     transmute_all(
+         funs(function(x){if (x == 1) deparse(substitute(x)) else NA})
+     )
Error in mutate_impl(.data, dots) : 
  Column `a` is of unsupported type function
Run Code Online (Sandbox Code Playgroud)

编辑:尝试#2:

> data_frame(a = c(NA, 1, NA, 1, 1), b=c(1, NA, 1, 1, NA)) %>%
+     transmute_all(
+         funs(
+             ((function(x){if (!is.na(x)) deparse(substitute(x)) else NA})(.))
+             )
+     )
# A tibble: 5 x 2
  a     b    
  <lgl> <chr>
1 NA    b    
2 NA    b    
3 NA    b    
4 NA    b    
5 NA    b    
Warning messages:
1: In if (!is.na(x)) deparse(substitute(x)) else NA :
  the condition has length > 1 and only the first element will be used
2: In if (!is.na(x)) deparse(substitute(x)) else NA :
  the condition has length > 1 and only the first element will be used
> 
Run Code Online (Sandbox Code Playgroud)

akr*_*run 6

一种选择是 map2

library(purrr)
map2_df(df1, names(df1), ~  replace(.x, .x==1, .y))
# A tibble: 5 x 2
#  a     b    
# <chr> <chr>
#1 NA    b    
#2 a     NA   
#3 NA    b    
#4 a     b    
#5 a     NA   
Run Code Online (Sandbox Code Playgroud)

或者正如@Moody_Mudskipper 评论的那样

imap_dfr(df1, ~replace(.x, .x==1, .y))
Run Code Online (Sandbox Code Playgroud)

base R,我们可以做

df1[] <- names(df1)[col(df1) *(df1 == 1)]
Run Code Online (Sandbox Code Playgroud)

数据

df1 <-  data_frame(a = c(NA, 1, NA, 1, 1), b=c(1, NA, 1, 1, NA))
Run Code Online (Sandbox Code Playgroud)

  • 或 `imap_dfr(df1, ~replace(.x, .x==1, .y))` 稍微更紧凑 (2认同)

小智 5

如果你想坚持使用dplyr你几乎已经有了的解决方案

library(dplyr)

df <- data_frame(a = c(NA, 1, NA, 1, 1), b = c(1, NA, 1, 1, NA))

df %>% 
    transmute_all(funs(ifelse(. == 1, deparse(substitute(.)), NA)))

#> # A tibble: 5 x 2
#>     a     b    
#>   <chr> <chr>
#> 1 <NA>  b    
#> 2 a     <NA> 
#> 3 <NA>  b    
#> 4 a     b    
#> 5 a     <NA>
Run Code Online (Sandbox Code Playgroud)