如何编程比较R中的整行? [英] How to programatically compare an entire row in R?

查看:128
本文介绍了如何编程比较R中的整行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有以下数据框:

data =
时间X1 X2 X3
1 1 0 0
2 1 1 1
3 0 0 1
4 1 1 1
5 0 0 0
6 0 1 1
7 1 1 1
8 0 0 0
9 1 1 1
10 0 0 0

I have the following dataframe in R:
data= Time X1 X2 X3 1 1 0 0 2 1 1 1 3 0 0 1 4 1 1 1 5 0 0 0 6 0 1 1 7 1 1 1 8 0 0 0 9 1 1 1 10 0 0 0

有没有办法编程选择那些等于0,1,1)?我知道可以通过执行 data [data $ X1 == 0&数据$ X2 == 1&数据$ X3 == 1,] 但是,在我的场景中,(0,1,1)是变量中的列表。我的最终目标是确定等于(0,1,1)的行数,或列表变量可以容纳的任何其他组合。

Is there a way to programatically select those rows that are equal to (0,1,1)? I know it can be done by doing data[data$X1 == 0 & data$X2 == 1 & data$X3 == 1,] but, in my scenario, (0,1,1) is a list in a variable. My ultimate goal here is to determine the number of rows that are equal to (0,1,1), or any other combination that list variable can hold.

谢谢!

Mariano。

推荐答案

这里有几个选项, code> merge :

Here's a couple of options using a merge:

merge(list(X1=0,X2=1,X3=1), dat)
#or
merge(setNames(list(0,1,1),c("X1","X2","X3")), dat)

甚至根据您要匹配的列使用位置索引:

Or even using positional indexes based on what columns you want matched up:

L <- list(0,1,1)
merge(L, dat, by.x=seq_along(L), by.y=2:4)

所有这些都返回:

#  X1 X2 X3 Time
#1  0  1  1    6

如果您的匹配变量都是相同的类型,您还可以通过矩阵比较来安全地执行,如:

If your matching variables are all of the same type, you could also safely do it via matrix comparison like:

dat[colSums(t(dat[c("X1","X2","X3")]) == c(0,1,1)) == 3,]

这篇关于如何编程比较R中的整行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆