% mutate(h = substr(h-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:01:19 25 4
gpt4 key购买 nike

我有一个这样的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com