Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

dplyr - Transform structure of data frame in R

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...