[英]How to match two columns of logical vectors within a data frame
Here's some dummy code and its pretty obvious output: 这是一些伪代码及其明显的输出:
xdupe <- as.logical(c("T", "F", "F", "F", "T", "T", "F"))
ydupe <- as.logical(c("T", "F", "F", "F", "F", "T", "T"))
cities <- c("Knox", "Whiteville", "Madison", "York", "Paris", "Corona", "Bakersfield")
df <- data.frame(cities, xdupe, ydupe)
df$cities <- as.character(df$cities)
> df
cities xdupe ydupe
1 Knox TRUE TRUE
2 Whiteville FALSE FALSE
3 Madison FALSE FALSE
4 York FALSE FALSE
5 Paris TRUE FALSE
6 Corona TRUE TRUE
7 Bakersfield FALSE TRUE
For some context, what xdupe and ydupe represent are logical values for duplicated x and y coordinates (longitude and latitude, respectively). 在某些情况下,xdupe和ydupe表示的是重复的x和y坐标(分别为经度和纬度)的逻辑值。
So what I need to be able to do is see which attributes in the data frame have TRUE values for both xdupe and ydupe. 因此,我需要做的就是查看数据框中哪些属性同时具有xdupe和ydupe的TRUE值。 In this particular case, that would be the cities Knox and Corona.
在这种情况下,那将是诺克斯和科罗纳这两个城市。 How can I compare xdupe and y dupe so that I can pull out all of the cities that have BOTH true values?
我该如何比较xdupe和y dupe,这样才能排除所有具有真实值的城市?
This can be done in a couple of ways. 这可以通过两种方法来完成。 One option is
&
. 一种选择是
&
。 It will become TRUE
only when all the elements are TRUE
. 它将成为
TRUE
只有当所有的元素都是TRUE
。 So, if we use xdupe & ydupe
, it will compare the corresponding elements of 'xdupe' and 'ydupe' and get TRUE
only when both elements are 'TRUE'. 所以,如果我们使用
xdupe & ydupe
,它会比较“xdupe”和“ydupe”的相应元素,并得到TRUE
只有当这两个元素是“真”。
i1 <- with(df, xdupe & ydupe)
Or another option is rowSums
of the subset of dataset that includes only the logical columns. 另一个选择是仅包含逻辑列的数据
rowSums
集的rowSums
。 As the binary representation for TRUE is 1 and FALSE is 0, when there are both TRUE for each corresponding element, it will result in 2. 由于TRUE的二进制表示为1而FALSE为0,因此每个对应的元素都为TRUE时,结果为2。
i1 <- rowSums(df[-1])==2
and then we subset the dataset 然后我们对数据集进行子集
Subdf <- df[i1,]
Subdf
# cities xdupe ydupe
#1 Knox TRUE TRUE
#6 Corona TRUE TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.