0

I have a data.frame like this

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

How do I count any level of VAR2 for each year?

What I want is a plot, where the x-axe is the year, and the y-axe is the count of any level in VAR2

Produnis
  • 489
  • 1
  • 5
  • 14

3 Answers3

3

The data.table solution

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])
Remi.b
  • 16,247
  • 25
  • 74
  • 153
3

The simplest way I can think of:

let dat = your data frame

with(dat,table(VAR1,VAR2))

The output will look something like this:

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

Hope this helps.

aaditya_n
  • 41
  • 2
1

There are a large number of ways and this question is undoubtedly a duplicate. What have you tried? You can use dcast in the reshape2 pacakge.

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
Simon O'Hanlon
  • 56,833
  • 13
  • 136
  • 180