r - 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。
解决方案
这是一种方法:
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
推荐阅读
- facebook - 如何使用 facebook 和 twitter 对 firebase 进行身份验证?
- php - 无法为从控制器到视图的 JSON 响应嵌入 $data
- codeigniter-3 - 当我在 php Codeigniter 中导出到 DOC 时,我视图中编写的所有代码也出现在 doc 中
- python - jupyter notebook:内核在 python 3 中已死
- javascript - 在地图中显示经纬度的点并弹出一个点的值
- django - 在 Django 中使用 db_index=True 设置索引名称
- python - Lark 中的布尔表达式解析器无法解析“a OR b OR c”
- java - Paho:并行连接创建导致连接下拉
- javascript - AngularJS - 在 Chrome 中选择文本触发父级中的 ng-click
- c# - Visual Studio 调试文件夹和生成的安装程序中的文件包含不同的 dll 文件