簡體   English   中英

使用 R 中數據框中的多列創建列聯表

[英]Creating a contingency table using multiple columns in a data frame in R

我有一個如下所示的數據框:

structure(list(ab = c(0, 1, 1, 1, 1, 0, 0, 0, 1, 1), bc = c(1, 
1, 1, 1, 0, 0, 0, 1, 0, 1), de = c(0, 0, 1, 1, 1, 0, 1, 1, 0, 
1), cl = c(1, 2, 3, 1, 2, 3, 1, 2, 3, 2)), .Names = c("ab", "bc", 
"de", "cl"), row.names = c(NA, -10L), class = "data.frame")

列 cl 表示集群關聯,變量 ab、bc 和 de 帶有二元答案,其中 1 表示是,0 - 否。

我正在嘗試創建一個表交叉表集群以及數據框中的所有其他列,即 ab、bc 和 de,其中集群成為列變量。 想要的輸出是這樣的

    1  2  3
 ab 1  3  2
 bc 2  3  1
 de 2  3  1

我嘗試了以下代碼:

with(newdf, tapply(newdf[,c(3)], cl, sum))

這為我提供了一次僅一列交叉表的值。 我的數據框有 1600 多列和 1 個簇列。 有人可以幫忙嗎?

使用dplyr一種方法是:

library(dplyr)
df %>% 
  #group by the varialbe cl
  group_by(cl) %>%
  #sum every column
  summarize_each(funs(sum)) %>%
  #select the three needed columns
  select(ab, bc, de) %>%
  #transpose the df
  t

輸出:

   [,1] [,2] [,3]
ab    1    3    2
bc    2    3    1
de    2    3    1

您的數據采用半長半寬格式,並且您希望它采用全寬格式。 如果我們首先將其轉換為全長格式,這是最簡單的:

library(reshape2)
df_long = melt(df, id.vars = "cl")
head(df_long)
#    cl variable value
# 1   1       ab     0
# 2   2       ab     1
# 3   3       ab     1
# 4   1       ab     1
# 5   2       ab     1
# 6   3       ab     0

然后我們可以將其轉換為寬格式,使用sum作為聚合函數:

dcast(df_long, variable ~ cl, fun.aggregate = sum)
#   variable 1 2 3
# 1       ab 1 3 2
# 2       bc 2 3 1
# 3       de 2 3 1

base R 中:

t(sapply(data[,1:3],function(x) tapply(x,data[,4],sum)))
#   1 2 3
#ab 1 3 2
#bc 2 3 1
#de 2 3 1

您還可以結合tidyr:gatherreshape2::meltxtabs來制作您的應急表

library(tidyr)
xtabs(value ~ key + cl, data = gather(df, key, value, -cl))
##     cl
## key  1 2 3
##   ab 1 3 2
##   bc 2 3 1
##   de 2 3 1

如果您更喜歡使用管道

df %>%
  gather(key, value, -cl) %>%
  xtabs(value ~ key + cl, data = .)

只是為了使用 dplyr 的 pivot_longer(取代了收集)按照 dickoa 寫的代碼進行更新:

library(dplyr)

df %>% 
pivot_longer(cols = ab:de,
          names_to = "key",
          values_to = "value") %>% 
xtabs(value ~ key + cl, data = .)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM