【问题标题】:New column using the column names as the values of the new one?使用列名作为新列的值的新列?
【发布时间】:2017-02-27 01:40:31
【问题描述】:

我有一个像下面这样的小标题。看到它使用字符“Y”作为值。

require(tidyverse)
df <- data_frame(a = c('Y', NA, 'Y'), b = c(NA, 'Y', NA))
df

# A tibble: 3 × 2
      a     b
  <chr> <chr>
1     Y  <NA>    
2  <NA>     Y
3     Y  <NA>

我想创建一个结合其他两个(或更多)的新列,但是更改“Y”以匹配列的名称。在这种情况下,“a”和“b”。比如这个

# A tibble: 3 × 3
      a     b    c
  <chr> <chr> <chr>
1     Y  <NA>    a
2  <NA>     Y    b
3     Y  <NA>    a

我非常有信心每行不超过一个“Y”。我不认为我可以使用 gathermutate 解决这个问题

【问题讨论】:

  • 之前问过很多次:names(df)[max.col(!is.na(df))]

标签: r tidyr tidyverse


【解决方案1】:

我们可以使用whicharr.ind=TRUE

ind <- which(!is.na(df), arr.ind = TRUE)
df$c <- names(df)[ind[,2][order(ind[,1])]]
df$c
#[1] "a" "b" "a"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-18
    • 2021-02-23
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多