问题描述
我有此数据帧:
df <- structure(list(number = 1:3, a_1 = c(1L, 4L, 7L), a_2 = c(2L,
5L, 8L), a_3 = c(3L, 6L, 9L)), class = "data.frame", row.names = c(NA,
-3L))
number a_1 a_2 a_3
1 1 1 2 3
2 2 4 5 6
3 3 7 8 9
我要变异anew_col
,并根据列number
与列名的字符串匹配的条件用值填充它。
所需输出:
number a_1 a_2 a_3 new_col
<int> <int> <int> <int> <int>
1 1 1 2 3 1
2 2 4 5 6 5
3 3 7 8 9 9
我尝试了str_extract
、str_detect
...但我做不到!
推荐答案
我们可以在paste
后面paste
将‘a_’改为‘number’
library(dplyr)
library(stringr)
df %>%
rowwise %>%
mutate(new_col = get(str_c('a_', number))) %>%
ungroup
-输出
# A tibble: 3 x 5
number a_1 a_2 a_3 new_col
<int> <int> <int> <int> <int>
1 1 1 2 3 1
2 2 4 5 6 5
3 3 7 8 9 9
将矢量化选项用于row/column
索引可能更好
df$newcol <- df[-1][cbind(seq_len(nrow(df)),
match(paste0("a_", df$number), names(df)[-1]))]