R-Dplyr-get()不适用于每一列,只使用第一个匹配项
我有一个DF,看起来像这样:R-Dplyr-get()不适用于每一列,只使用第一个匹配项,r,dplyr,R,Dplyr,我有一个DF,看起来像这样: V1 V2 V3 V4 V5 V6 1251 V5 12 7 13 91 126 V5 17 9 75 90 912 V6 55 34 88 22 我正在尝试获取V2中引用的列的值 df %>% mutate(V2_ref_value = get(V2)) %>% select(V1, V2, V2_ref_value) 对于第1行和第2行,第V2列引用了V5。对于第3行,V2引用V6 使用dp
V1 V2 V3 V4 V5 V6
1251 V5 12 7 13 91
126 V5 17 9 75 90
912 V6 55 34 88 22
我正在尝试获取V2中引用的列的值
df %>%
mutate(V2_ref_value = get(V2)) %>%
select(V1, V2, V2_ref_value)
对于第1行和第2行,第V2列引用了V5
。对于第3行,V2引用V6
使用dplyr,我试图获得V2中引用的列的相应值
df %>%
mutate(V2_ref_value = get(V2)) %>%
select(V1, V2, V2_ref_value)
这将返回一个奇数df:
V1 V2 V2_ref_value
1251 V5 13
126 V5 75
912 V6 88
第1行和第2行的正确值显示了,但第3行也显示了第V5列中的值,而不是其引用的第V6列中的值
正确的输出应为:
V1 V2 V2_ref_value
1251 V5 13
126 V5 75
912 V6 22
有人知道为什么会发生这种情况,或者我可以如何修复这种情况吗?您需要按行执行:
df %>%
rowwise() %>%
mutate(V2_ref_value = get(V2))
V1 V2 V3 V4 V5 V6 V2_ref_value
<int> <chr> <int> <int> <int> <int> <int>
1 1251 V5 12 7 13 91 13
2 126 V5 17 9 75 90 75
3 912 V6 55 34 88 22 22
我们可以在
base R
df$V2_ref_value <- as.numeric(df[cbind(seq_len(nrow(df)),
match(df$V2, names(df)))])
数据
df
df
# V1 V2 V3 V4 V5 V6 V2_ref_value
#1 1251 V5 12 7 13 91 13
#2 126 V5 17 9 75 90 75
#3 912 V6 55 34 88 22 22
df <- structure(list(V1 = c(1251L, 126L, 912L), V2 = c("V5", "V5",
"V6"), V3 = c(12L, 17L, 55L), V4 = c(7L, 9L, 34L), V5 = c(13L,
75L, 88L), V6 = c(91L, 90L, 22L)), class = "data.frame", row.names = c(NA,
-3L))