-1

I am new to stack overflow and sorry if I am not asking question properly. I have two columns country and Year.

    INDIA 1970
    USA   1970
    USA   1971
    INDIA 1970
    .
    .
    UK    1972

I want new data frame like this and I need to fill it with occurrences.

            1970 1971 1972.... 
    INDIA    2
    USA      1     1
    UK                1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

1 Answers1

3

An option could be to use reshape2::dcast with fun.aggregate argument set as length:

library(reshape2)
dcast(df, Country~Year, length)
#   Country 1970 1971 1972
# 1   INDIA    2    0    0
# 2      UK    0    0    1
# 3     USA    1    1    0

Data:

df <- read.table(text = 
"Country Year
INDIA 1970
USA   1970
USA   1971
INDIA 1970
UK    1972",
header = TRUE, stringsAsFactors = FALSE)
MKR
  • 19,739
  • 4
  • 23
  • 33