使用dplyr的transmute_all将列值替换为列名 [英] Replace column values with column name using dplyr's transmute_all
本文介绍了使用dplyr的transmute_all将列值替换为列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
数据集包含许多包含NA或1的值的列,如下所示:
Data set contains many columns containing values which are either NA or 1, kind of like this:
> 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
所需的输出:将所有1个值替换为列名作为字符串,
Desired output: replace all the 1 values with the name of the column as a string,
> 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>
这是我在transmute_all中使用匿名函数的尝试:
here's my attempt using an anonymous function in 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
尝试#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
>
推荐答案
如果您想坚持使用 dplyr
解决方案,您几乎已经拥有了它
If you want to stick with a dplyr
solution you almost already had it
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>
这篇关于使用dplyr的transmute_all将列值替换为列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文