简体   繁体   English

聚合因子水平计数 - 按因子计算

[英]Aggregating factor level counts - by factor

I have been trying to make a table displaying the counts of factor levels by another factor. 我一直试图用另一个因素制作一个显示因子水平计数的表格。 For this, I looked on dozens of pages, questions... trying to use functions in some packages (dplyr, reshape) to get the job done, without any success in using them correctly. 为此,我查看了几十页,问题......尝试在某些软件包中使用函数(dplyr,reshape)来完成工作,没有成功正确使用它们。

That's what I got: 这就是我得到的:

# my data:
var1 <- c("red","blue","red","blue","red","red","red","red","red","red","red","red","blue","red","blue")
var2 <- c("0","1","0","0","0","0","0","0","0","0","1","0","0","0","0")
var3 <- c("2","2","1","1","1","3","1","2","1","1","3","1","1","2","1")
var4 <- c("0","1","0","0","0","0","1","0","1","1","0","1","0","1","1")
mydata <- data.frame(var1,var2,var3,var4)
head(mydata)

Attempt n+1: displays only the total counts of factors by another factor. 尝试n + 1:仅显示因子的总计数。

t(aggregate(. ~ var1, mydata, sum))

      [,1]   [,2] 
var1 "blue" "red"
var2 " 5"   "12" 
var3 " 5"   "18" 
var4 " 6"   "16" 

Attempt n+2: it's the correct format but I couldn't get it to work on more than one factor. 尝试n + 2:这是正确的格式,但我不能让它在多个因素上工作。

library(dplyr)
data1 <- ddply(mydata, c("var1", "var3"), summarise,
            N    = length(var1))
library(reshape)
df1 <- cast(data1, var1 ~ var3, sum)
df1 <- t(df1)
df1

   blue red
1    3   6
2    1   3
3    0   2

What I would like is: 我想要的是:

        blue red
var2.0    3  10
var2.1    1   1
var3.1    3   6
var3.2    1   3
var3.3    0   2
var4.0    2   6
var4.1    2   5

How can I get this format? 我怎样才能获得这种格式? So many thanks in advance, 非常感谢提前,

We can melt the dataset by 'var1' and then use table 我们可以通过'var1'来melt数据集然后使用table

library(reshape2)
tbl <- table(transform(melt(mydata, id.var="var1"),
        varN = paste(variable, value, sep="."))[c(4,1)])
names(dimnames(tbl)) <- NULL
tbl 
#
#         blue red
#  var2.0    3  10
#  var2.1    1   1
#  var3.1    3   6
#  var3.2    1   3
#  var3.3    0   2
#  var4.0    2   6
#  var4.1    2   5

Or using dplyr/tidyr , we convert the dataset from 'wide' to 'long' format with gather , then unite the columns ('var', 'val') to create 'varV', get the frequency ( tally ) after grouping by 'var1' and 'varV', and then spread to 'wide' format. 或使用dplyr/tidyr ,我们把数据集从“宽”到“长”格式与gather ,然后unite列(“var”或“VAL”)创建“天花病毒”,得到的频率( tally通过分组之后) 'var1'和'varV',然后spread到'wide'格式。

library(dplyr)
library(tidyr)
gather(mydata, var, val, -var1) %>% 
           unite(varV,var, val, sep=".") %>%
           group_by(var1, varV) %>% 
           tally() %>% 
           spread(var1, n, fill = 0)
#    varV  blue   red
#   <chr> <dbl> <dbl>
#1 var2.0     3    10
#2 var2.1     1     1
#3 var3.1     3     6
#4 var3.2     1     3
#5 var3.3     0     2
#6 var4.0     2     6
#7 var4.1     2     5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM