gpt4 book ai didi

使用 dplyr 的 transmute_all 将列值替换为列名称

转载 作者:行者123 更新时间:2023-12-02 17:54:55 24 4
gpt4 key购买 nike

数据集包含许多包含 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
>

最佳答案

一个选项是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

或者正如 @Moody_Mudskipper 评论的那样

imap_dfr(df1, ~replace(.x, .x==1, .y))
<小时/>

base R中,我们可以做到

df1[] <- names(df1)[col(df1) *(df1 == 1)]

数据

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

关于使用 dplyr 的 transmute_all 将列值替换为列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50138295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com