[英]Collapse columns before aggregating by count
我想的是一個非常簡單的問題,但是經過大量的木板搜索/閱讀教程后,我根本無法弄清楚。
我有一個df,第5到12列中的名稱條目均為一種類型。 它們是名稱字符串(例如,請參見下文)。 我要做的就是使用聚合或ddply(或另一個,如果更簡單...)函數折疊這些列,然后返回每個唯一條目的計數。
ID | Name 1 | Name 2 | Name 3
Row 1: 278 | John | Tim | Mike
Row 2: 279 | Tim | Steve | John
Row 3: 280 | Tim | Doug | Dave
因此,理想情況下,我會得到:
Tim | 3
John | 2
Mike | 1
etc. | 1
我知道這對於一欄如何工作:
counts=aggregate(numeric(nrow(df)), df[c(4)], length)
但是,當我在多列中使用相似的行時,它將返回七個列的唯一組合,而不是具有聚集的唯一條目和總和的nx2向量。
counts2=aggregate(numeric(nrow(df)),df[c(5:12)],FUN = function(x) length(unique(x)))
非常感謝您的幫助。
這是使用dplyr
和tidyr
一種方法
foo <- data.frame(id = 278:280,
Name1 = c("John", "Tim", "Mike"),
Name2 = c("Tim", "Steve", "John"),
Name3 = c("Tim", "Doug", "Dave"),
stringsAsFactors = FALSE)
library(dplyr)
library(tidyr)
foo %>%
gather(var, names, -id) %>%
count(names)
# names n
#1 Dave 1
#2 Doug 1
#3 John 2
#4 Mike 1
#5 Steve 1
#6 Tim 3
我沒有趕上Hadley提出的新軟件包的速度,但是這是我使用reshape2
軟件包解決問題的方法。 想法(與上面相同)是將列折疊為一列,然后匯總該數據:
library(reshape2)
dcast(data = melt(foo, id.vars = "id"), value ~ .)
#---
value .
1 Dave 1
2 Doug 1
3 John 2
4 Mike 1
5 Steve 1
6 Tim 3
讀取數據:
txt <- "ID | Name 1 | Name 2 | Name 3
Row 1: 278 | John | Tim | Mike
Row 2: 279 | Tim | Steve | John
Row 3: 280 | Tim | Doug | Dave "
dat <- read.csv(text = txt, sep = "|", strip.white = TRUE)
您可以在未列出的列上使用as.data.frame
表方法。
u <- unlist(dat[-1])
as.data.frame(table(levels(u)[u]))
# Var1 Freq
# 1 Dave 1
# 2 Doug 1
# 3 John 2
# 4 Mike 1
# 5 Steve 1
# 6 Tim 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.