简体   繁体   中英

R: Combine rows with the same id, and expand the columns

**I got a data set like this: (and the name of the data set is called "2010.csv")

ID  year month score_1 score_2

100 2010 1      93      85

200 2010 1      94      93

100 2010 2      84      90

200 2010 2      90      90

**What I want is this:

ID year month score_1 score_2  year month score_1 score_2

100 2010  1     93      85     2010   2      84     90

200 2010  1     94      93     2010   2      90     90

Could anyone help me to do it in R? Thanks!

Using the data shown reproducibly in the Note at the end, first reshape the data. The reshape command will repeat the ID and year columns so remove all but the first instance. Then clean up the names. If not having the names exactly as in the question and having duplicate ID and year columns are ok then you could just use the first line. No packages are used.

r <- reshape(DF, dir = "wide", idvar = 1:2, timevar = 3)
r <- r[-tail(grep("year|ID", names(r)), -2)]
names(r) <- sub("\\..*", "", names(r))
r

giving this data.frame:

   ID year month score_1 score_2 month score_1 score_2
1 100 2010     1      93      85     2      84      90
2 200 2010     1      94      93     2      90      90

Note

Lines <- "
ID  year month score_1 score_2
100 2010 1      93      85
200 2010 1      94      93
100 2010 2      84      90
200 2010 2      90      90"
DF <- read.table(text = Lines, header = TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM