【问题标题】:subset data only if observations of 2 variables match with each other in R仅当 R 中 2 个变量的观察值彼此匹配时才子集数据
【发布时间】:2019-08-24 05:56:33
【问题描述】:

我有这样的数据:

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 x 5 列联表中分离出来来创建 2 x 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

【问题讨论】:

  • 您的尝试中缺少)。试试df[df$a %in% c("blue", "red") &amp; df$b %in% c("blue","red"), ]。你会得到想要的结果。
  • 好的,谢谢。我纠正并运行。但结果还是一样。
  • 抱歉,这是我创建示例输出时的错误。
  • 你能更新你的示例输入吗?你可以分享dput(head(df, 20))
  • 喜欢out &lt;- subset(df, sp.tree %in% c("Pinus pinea", "Quercus ilex") &amp; sp.near %in% c("Pinus pinea", "Quercus ilex")); table(droplevels(out)) ?

标签: r if-statement conditional subset


【解决方案1】:

您可以添加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.

【讨论】:

    【解决方案2】:

    这应该可行!

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

    【讨论】:

    • 是的,这就是我尝试过的,但仍然有一些其他颜色与蓝色或红色相匹配,例如(绿色=蓝色或橙色=蓝色)。这不是我想要的。我想要像 blue=blue、red=red 或 red=blue 这样的观察结果。
    【解决方案3】:

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

    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
    

    【讨论】:

    • 用我的数据,所有的观察结果都出来了,除了最后 2 x 2 矩阵(只有它们是 0)
    • 对不起,我没有关注。我使用了你的样本数据。
    • 没关系。感谢您的回复和帮助!
    猜你喜欢
    • 2013-12-03
    • 2023-01-27
    • 2022-06-17
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    相关资源
    最近更新 更多