首页 > 解决方案 > dplyr:使用来自其他指定列的值创建新列

问题描述

我有一个小标题:

library(tibble)
library(dplyr)

(
  data <- tibble(
    a = 1:3,
    b = 4:6,
    mycol = c('a', 'b', 'a')
  )
)
#> # A tibble: 3 x 3
#>       a     b mycol
#>   <int> <int> <chr>
#> 1     1     4 a    
#> 2     2     5 b    
#> 3     3     6 a

使用dplyr::mutate我想创建一个名为的新列value,它使用来自列a或的值b,具体取决于列中指定的mycol列名。

(
  desired <- tibble(
    a = 1:3,
    b = 4:6,
    mycol = c('a', 'b', 'a'),
    value = c(1, 5, 3)
  )
)
#> # A tibble: 3 x 4
#>       a     b mycol value
#>   <int> <int> <chr> <dbl>
#> 1     1     4 a         1
#> 2     2     5 b         5
#> 3     3     6 a         3

在这里,我们只是一直使用列中的值a

data %>%
  mutate(value = a)
#> # A tibble: 3 x 4
#>       a     b mycol value
#>   <int> <int> <chr> <int>
#> 1     1     4 a         1
#> 2     2     5 b         2
#> 3     3     6 a         3

在这里,我们只是将值分配给mycol新列,而不是从适当的列中获取值。

data %>%
  mutate(value = mycol)
#> # A tibble: 3 x 4
#>       a     b mycol value
#>   <int> <int> <chr> <chr>
#> 1     1     4 a     a    
#> 2     2     5 b     b    
#> 3     3     6 a     a

我尝试了 , 等的各种组合!!quo()但我不完全理解 NSE 的幕后情况。

@Jaap 已将此标记为重复,但我仍然希望看到使用 NSE 的 dplyr/tidyverse 方法,而不是尽可能使用 base R。

标签: rdplyrnse

解决方案


这是一种方法:

df %>%
  mutate(value = ifelse(mycol == "a", a, b))
#output
# A tibble: 3 x 4
      a     b mycol value
  <int> <int> <chr> <int>
1     1     4 a         1
2     2     5 b         5
3     3     6 a         3

这是基础 R 中更通用的方法

df$value <- diag(as.matrix(df[,df$mycol]))

更复杂的例子:

df <- tibble(
    a = 1:4,
    b = 4:7,
    c = 5:8,
    mycol = c('a', 'b', 'a', "c"))

df$value <- diag(as.matrix(df[,df$mycol]))
#output
# A tibble: 4 x 5
      a     b     c mycol value
  <int> <int> <int> <chr> <int>
1     1     4     5 a         1
2     2     5     6 b         5
3     3     6     7 a         3
4     4     7     8 c         8

推荐阅读