将值命名为值

时间:2017-05-29 10:38:33

标签: r dplyr

我正在使用dplyr,我有这样一个类似的东西:

df<- data_frame(one= c(1, NA, 1),
       two= c(NA,NA,1),
       three= c(1, 1,1)
       )
----------------------------
# A tibble: 3 x 3
      one   two  three
     <dbl> <dbl> <dbl>
 1     1    NA     1
 2    NA    NA     1
 3     1     1     1
----------------------------

我需要获得这样的东西:

----------------------------
# A tibble: 3 x 3
      one    two    three
     <dbl>  <dbl>   <dbl>
 1    one    NA     three
 2    NA     NA     three
 3    one    two    three
----------------------------

所以我可以为每列使用带有mutate的ifelse函数:

df %>%
      one= ifelse(!is.na(one),'one', NA ),
      two= ifelse(!is.na(two),'two', NA ),
      three= ifelse(!is.na(three),'three', NA ),

但是在我的真实df中我有很多专栏,那么这个wat效率非常低。 我需要一些更优雅的东西,使用mutate_at和列名,但它看起来很难。 我试图在很多方面做到这一点,但每次我都会收到错误。 有什么建议吗?

1 个答案:

答案 0 :(得分:1)

如果数据集中只有1和NA,请将col(df)与数据集unlist相乘,并根据索引将其替换为names数据集并将其分配回原始数据

df[] <- names(df)[unlist(col(df)*df)]
df
# A tibble: 3 x 3
#    one   two three
#  <chr> <chr> <chr>
#1   one  <NA> three
#2  <NA>  <NA> three
#3   one   two three

或者使用tidyverse,我们可以为每列(map2_df的{​​{1}})

执行此操作
purrr