我有这样的数据:
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
您可以将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
更多信息在这里。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句