基于R中的不同数据帧的值进行子集

时间:2013-02-26 19:22:33

标签: r dataframe

如果行中的每个值都大于不同数据帧中的相应行,我想要对数据进行子集化。我还需要跳过一些顶行。这些先前的问题对我没有帮助,但它是相关的:

Subsetting a data frame based on contents of another data frame

Subset data using information from a different data frame [r]

> A
     name1 name2
cond   trt  ctrl
hour     0     3
A        1     1
B       10     1
C        1     1
D        1     1
E       10    10
> B
     name1 name2
cond   trt  ctrl
hour     0     3
A        1     1
B        1    10
C        1     1
D        1     1
E        1     1

我想要这个。只有A中所有值大于B的行:

     name1 name2
cond   trt  ctrl
hour     0     3
E       10    10

我试过这3行:

subset(A, TRUE, select=(A[3:7,] > B[3:7,]))
subset(A, A > B)
A[A[3:7,] > B[3:7,]]

非常感谢。以下是生成数据的代码:

A <- structure(list(name1 = c("trt", "0", "1", "10", "1", "1", "10"
), name2 = c("ctrl", "3", "1", "1", "1", "1", "10")), .Names = c("name1", 
"name2"), row.names = c("cond", "hour", "A", "B", "C", "D", "E"
), class = "data.frame")
B <- structure(list(name1 = c("trt", "0", "1", "1", "1", "1", "1"), 
    name2 = c("ctrl", "3", "1", "10", "1", "1", "1")), .Names = c("name1", 
"name2"), row.names = c("cond", "hour", "A", "B", "C", "D", "E"
), class = "data.frame")
#############跟进问题于2013年2月28日提出

Error when subsetting based on adjusted values of different data frame in R

4 个答案:

答案 0 :(得分:5)

N <- nrow(A)
cond <- sapply(3:N, function(i) sum(A[i,] > B[i,])==2)
rbind(A[1:2,], subset(A[3:N,], cond))

答案 1 :(得分:3)

我认为最好使用SQL进行这种表间过滤。它干净且易读(您遵守规则逻辑)。

 library(sqldf)
sqldf('SELECT DISTINCT A.*
        FROM A,B
        WHERE A.name1   > B.name1
        AND    A.name2  > B.name2')
  name1 name2
1   trt  ctrl
2    10    10

答案 2 :(得分:3)

必要的data.table解决方案:

library(data.table)

# just to preserve the order, non-alphabetically
idsA <- factor(rownames(A), levels=rownames(A))
idsB <- factor(rownames(B), levels=rownames(B))

# convert to data.table with id
ADT <- data.table(id=idsA, A, key="id")
BDT <- data.table(id=idsB, B, key="id")

# filter as needed
ADT[BDT][name1 > name1.1 & name2 > name2.1, list(id, name1, name2)]

答案 3 :(得分:2)

如果我重命名您的矩阵amatbmat,那么

amat[which(sapply(1:nrows(amat),function(x) prod(amat[x,]>bmat[x,]))==1),]
[1] 10 10

如果需要,您可以重新打开'小时'行。