r - 使用 col 的值从另一个 col 中选择值,放入 R 中的新 df

标签 r

我有一个这样的df

name <- c("Fred","Mark","Jen","Simon","Ed")
a_or_b <- c("a","a","b","a","b")
abc_ah_one <- c(3,5,2,4,7)
abc_bh_one <- c(5,4,1,9,8)
abc_ah_two <- c(2,1,3,7,6)
abc_bh_two <- c(3,6,8,8,5)
abc_ah_three <- c(5,4,7,6,2)
abc_bh_three <- c(9,7,2,1,4)
def_ah_one <- c(1,3,9,2,7)
def_bh_one <- c(2,8,4,6,1)
def_ah_two <- c(4,7,3,2,5)
def_bh_two <- c(5,2,9,8,3)
def_ah_three <- c(8,5,3,5,2)
def_bh_three <- c(2,7,4,3,0)
df <- data.frame(name,a_or_b,abc_ah_one,abc_bh_one,abc_ah_two,abc_bh_two,
abc_ah_three,abc_bh_three,def_ah_one,def_bh_one,
def_ah_two,def_bh_two,def_ah_three,def_bh_three)

我想使用“a_or_b”列中的值为每个“abc”(一、二和三)选择相应的“ah/bh”列中的值,并将其放入新数据中框架。例如,Fred 在新 df 的行中将具有值 3、2 和 5。这些值表示 abc 列的每个“ah”类别的值。 Jen 在她的 a_or_b 列中有“b”,她的所有“bh”值都来自她的 abc 列,用于她在新 df 中的行。这是我想要的输出:

combo_one <- c(3,5,1,4,8)
combo_two <- c(2,1,8,7,5)
combo_three <- c(5,4,2,6,4)
df2 <- data.frame(name,a_or_b,combo_one,combo_two,combo_three)

我已经尝试使用 sapply 进行此操作。以下为我提供了每行的 df[grep("abc",colnames(df),fixed=TRUE)] 的正确列正确索引的矩阵:

sapply(paste0(df$a_or_b,"h"),grep,colnames(df[grep("abc",colnames(df),fixed=TRUE)])) 

最佳答案

首先,我们将您的数据收集成整齐的长格式,然后将列分解为有用的内容。之后过滤就很简单了,如果有必要,我们可以转换回一个困难的宽格式:

library(dplyr)
library(tidyr)

gather(df, key = "var", value = "val", -name, -a_or_b) %>%
  separate(var, into = c("combo", "h", "ind"), sep = "_") %>%
  mutate(h = substr(h, 1, 1)) %>%
  filter(a_or_b == h, combo == "abc") %>%
  arrange(name) -> result_long
result_long
#     name a_or_b combo h   ind val
# 1     Ed      b   abc b   one   8
# 2     Ed      b   abc b   two   5
# 3     Ed      b   abc b three   4
# 4   Fred      a   abc a   one   3
# 5   Fred      a   abc a   two   2
# 6   Fred      a   abc a three   5
# 7    Jen      b   abc b   one   1
# 8    Jen      b   abc b   two   8
# 9    Jen      b   abc b three   2
# 10  Mark      a   abc a   one   5
# 11  Mark      a   abc a   two   1
# 12  Mark      a   abc a three   4
# 13 Simon      a   abc a   one   4
# 14 Simon      a   abc a   two   7
# 15 Simon      a   abc a three   6

spread(result_long, key = ind, value = val) %>%
  select(name, a_or_b, one, two, three)
#    name a_or_b one two three
# 1    Ed      b   8   5     4
# 2  Fred      a   3   2     5
# 3   Jen      b   1   8     2
# 4  Mark      a   5   1     4
# 5 Simon      a   4   7     6

关于r - 使用 col 的值从另一个 col 中选择值,放入 R 中的新 df,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50441369/

相关文章:

R CMD检查: Skip 'checking re-building of vignette outputs'

r - dplyr date as.numeric 奇怪的行为

r - 提示用户无需等待

RStudio 查看器 Pane 不工作?

r - 如何在 r 中执行条件查找?

r - getSymbols 未按预期返回数据

r - 如何使用 R 函数将向量转换为矩阵?

r - 从统计测试中提取输出

r - 将一个字符列一分为二并重复

r - 在 R 中使用多核来分析 GWAS 数据