Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a data frame with the following columns:

**Columns   Country   Year   Number_of_deaths**
**Data**      US      2000    25
              US      2001    30
              UK      2000    30
              UK      2001    21

I want to convert this to the following format:

**Columns: Country   2000   2001   2002   2003   2004**
**Data**     US        25     30     35     40     25
             UK        30     21     21     23     45

Can somebody give me sample code in R to do this? Any package is fine. Your help will be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
197 views
Welcome To Ask or Share your Answers For Others

1 Answer

A small illustration as requested:

library(tidyr)
# creating sample data
dt = data.frame(country = rep(LETTERS[1:2], each=2),
                year = 2000:2003,
                num = c(25,30,30,21))
dt %>% spread(year, num)
#   country 2000 2001 2002 2003
# 1       A   25   30   NA   NA
# 2       B   NA   NA   30   21

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...