在 R 中,我有一个字符向量 v
,其值是数据帧 rain
的 colnames(rain)
的所有元素。我想使用 v
创建一个新向量 chosen
其值满足 chosen[i] == rain[i, v[i]]
无需诉诸循环,最好使用 tidyverse
方法。
例如,如果我有:
library(tidyverse)
rain <- tibble(ceres = c(0, 1, 0, 1.5, 3),
mond = c(0, 0, 0.5, 0, 0),
els = c(1, 2, 1, 0, 1))
v <- c("els", "ceres", "els", "mond", "ceres")
我希望在选择中返回:
> chosen
# els ceres els mond ceres
# 1 1 1 0 3
最佳答案
你可以做
rain %>%
mutate(id = row_number()) %>%
pivot_longer(-id) %>%
inner_join(tibble(id = seq_along(v), name = v))
返回
# A tibble: 5 x 3
id name value
<int> <chr> <dbl>
1 1 els 1
2 2 ceres 1
3 3 els 1
4 4 mond 0
5 5 ceres 3
添加
pull(value, name)
返回命名向量
#> els ceres els mond ceres
#> 1 1 1 0 3
关于r - 使用行列索引对从数据框中的不同列中选择值的 Tidyverse 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68713330/