【发布时间】:2018-05-02 15:27:14
【问题描述】:
数据集包含许多包含 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
期望的输出:用列名作为字符串替换所有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>
这是我在 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
>
【问题讨论】: