dplyr:使用其他指定列中的值创建新列

时间:2018-09-01 11:12:17

标签: r dplyr mutate nse

我有个小标题:

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的新列,该列使用ab列中的值,具体取决于指定的列名在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而不是使用base R的dplyr / tidyverse方法。

1 个答案:

答案 0 :(得分:1)

这是一种方法:

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
相关问题