![](/img/trans.png)
[英]How to create a cross tabulation table between two variables with the counts in R?
[英]Cross table in R to find the relationship of two variables
我正在嘗試為我的數據框中的兩個項目形成一個交叉表,但它們並不方便地放在兩列中,而是它們是列內的元素,必須過濾掉才能繼續使用交叉表。
例如
column titles: Gender, Favourite Fruit
column 1: F,M,M,M,F,M,F,M,M,F
column 2: apple, pear, pear, grapes, apple, banana, peach, apple, pear, grapes
我想為女性和蘋果做一個交叉表,看看是否有關系。 我應該如何 go 這樣做?
謝謝! 艾美獎
有很多方法可以做到這一點,但最重要的是table()
function。
下面是一些假數據:
set.seed(123)
df <- data.frame(gender = sample(c("M", "F"), 1000, replace = T ),
fruit = sample(c("apple", "grapes", "banana", "pear"), 1000, replace = T) )
table()
function 是創建交叉表的好方法。 例如:
table(df)
fruit
gender apple banana grapes pear
F 134 122 128 109
M 114 131 127 135
你可以用這個 function 做很多事情。 要獲得您想要的東西,您可以在 function 的 arguments 中創建命名邏輯向量。
table(Female = df$gender == "F", Apple = df$fruit == "apple")
Apple
Female FALSE TRUE
FALSE 393 114
TRUE 359 134
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.