仅当R中2个变量的观察值彼此匹配时才是子集数据

问题描述 投票:1回答:3

我有这样的数据:

a <- c("blue", "red", "green", "blue","cyan")
b <- c("red","red","green","blue", "orange")
df <- data.frame(a,b)
df

      a      b
1  blue    red
2   red    red
3 green  green
4  blue   blue
5  cyan orange

如果蓝色和红色相互匹配并且自己观察,我试图对行进行子集化。

我正在尝试下面的代码,但当我看到使用表函数检查它们时,仍然有一些其他颜色匹配这些颜色之一。

 sub <- df[df$a %in% c("blue", "red" & df$b %in% c("blue","red"), ]
 table(sub$a, sub$b)

这对我来说非常棘手。如果蓝色和红色相互匹配并自己观察,我怎么能告诉R到子集?

期望的输出是:

      a      b
1  blue    red
2   red    red
3  blue   blue

这样做的最终目标是通过将5乘5列联表分开来创建2乘2列联表。如果有另一个建议要做到这一点,那将非常感激。

提前致谢!

这就是我所说的我不想要的。我只想保持观察蓝色和红色观察。我不想要任何绿色,橙色,青色的观察。

            Blue        Red            Green        Orange   Cyan
  Blue       28          39              32            3        1  
  Red        47         244             184           56        3
  Green      0           0               0            0         0
  Orange     0           0               0            0         0
  Cyan       0           0               0            0         0
r if-statement conditional subset
3个回答
2
投票

您可以添加droplevels()函数,如下所示:

# here the markus solution
twobytwo <- df[which(df$a %in% c("blue", "red") & df$b %in% c("blue","red")), ]
#here the droplevels, that removes the unused level
table(droplevels(twobytwo))

         b
a      blue red
  blue    1   1
  red     0   1

更多信息here


0
投票

这应该工作!

output <- df[df$a %in% c('red','blue') & df$b %in% c('red','blue'),]

0
投票

你可以尝试使用data.frame过滤你的grepl

require(tidyverse)

result <- df %>% 
  varhandle::unfactor() %>%
  filter(grepl(pattern = paste(c("red", "blue"), collapse="|"), a) |
         grepl(pattern = paste(c("red", "blue"), collapse="|"), b))

result
     a    b
1 blue  red
2  red  red
3 blue blue

table(result)
      b
a      blue red
  blue    1   1
  red     0   1
© www.soinside.com 2019 - 2024. All rights reserved.