gpt4 book ai didi

r - 根据向量定义的多列中的值选择行

转载 作者:行者123 更新时间:2023-12-01 12:42:37 24 4
gpt4 key购买 nike

我有以下数据框

df <- data.frame(A1 = c("A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B"), 
B2 = c("C","D","C","D","C","D","C","D","C","D","C","D","C","D","C","D","C","D","C","D"),
C3 = c("E","F","E","F","E","F","E","F","E","F","E","F","E","F","E","F","E","F","E","F"),
D4=c(1,12,5,41,45,4,5,6,12,7,3,4,6,8,12,4,12,1,6,7))

我想对前 3 列与向量 c("A","C","E") 匹配的所有行进行子集化

我试过用它,但它不起作用

vct <- c("A","C","E")
df[which(df[1:3] == vct)]

最佳答案

你或许可以使用paste(或interaction):

vct <- c("A","C","E")
do.call(paste, df[1:3]) %in% paste(vct, collapse = " ")
# [1] TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE
# [12] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
df[do.call(paste, df[1:3]) %in% paste(c("A", "C", "E"), collapse = " "), ]
# A1 B2 C3 D4
# 1 A C E 1
# 3 A C E 5
# 5 A C E 45
# 7 A C E 5
# 9 A C E 12

## with "interaction"
df[interaction(df[1:3], drop=TRUE) %in% paste(vct, collapse = "."), ]

你也可以这样做:

df[with(df, A1 == "A" & B2 == "C" & C3 == "E"), ]

关于r - 根据向量定义的多列中的值选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22839693/

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