【问题标题】:How to count levels of a factor in a data.frame, grouped by another value of that data.frame [GNU R] [duplicate]如何计算data.frame中因子的级别,按该data.frame的另一个值分组[GNU R] [重复]
【发布时间】:2013-05-17 08:10:35
【问题描述】:

我有一个这样的data.frame

VAR1 VAR2
1999 USA
1999 USA
1999 UK
2000 GER
2000 USA
2000 GER
2000 USA
2001 USA

我如何计算每年的任何级别的 VAR2?

我想要的是一个图,其中 x 轴是年份,y 轴是 VAR2 中任何级别的计数

【问题讨论】:

  • 并检查此question 以了解另一个类似的重塑问题。

标签: r


【解决方案1】:

data.table 解决方案

library(data.table)

new.dat = data.table(dat)[,length(unique(var2)),by=var1]
new.dat=as.matrix(new.dat)
plot(x=new.dat[,1],y=new.dat[,2])

【讨论】:

    【解决方案2】:

    我能想到的最简单的方法:

    让 dat = 你的数据框

    with(dat,table(VAR1,VAR2))
    

    输出将如下所示:

          VAR2
    VAR1   GER UK USA
      1999   0  1   2
      2000   2  0   2
      2001   0  0   1
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      有很多方法,这个问题无疑是重复的。你试过什么?您可以在reshape2 pacakge 中使用dcast

      require(reshape2)
      dcast( df , Country ~ Year , length )
      
      #  Country 1999 2000 2001
      #1     GER    0    2    0
      #2      UK    1    0    0
      #3     USA    2    2    1
      

      【讨论】:

      • @Produnis 欢迎您!
      • 用ggplot绘制这个数据,这个代码对我有用:ggplot(df, aes(x=factor(Year),fill=Country)) + geom_bar(position="dodge")跨度>
      猜你喜欢
      • 1970-01-01
      • 2019-01-27
      • 2018-10-23
      • 1970-01-01
      • 2015-06-17
      • 2018-04-20
      • 2020-10-29
      • 1970-01-01
      • 2020-10-29
      相关资源
      最近更新 更多