2017-01-25 113 views
1

我已經設置了下面的示例數據:合併記錄

data.frame(SEX=c("M","F","M","F"),COMPLAINT=c("headache","headache", "dizziness", "dizziness"), 
      reports=c(5,4,9,12), users = c(1250,3460,2500,1850)) 

    SEX COMPLAINT reports users 
1 M headache  5 1250 
2 F headache  4 3460 
3 M dizziness  9 2500 
4 F dizziness  12 1850 

我的問題是如何合併行1和2,以及3和4,使我的數據幀如下:

COMPLAINT reports_male reports_female users_male users_female 
1 headache   5    4  1250   3460 
2 dizziness   9    12  2500   1850 

任何人都有一個快速的解決方案,我可以使用一個(很多)較大的數據集?

回答

3

我們可以使用dcastdata.table可以採取多種value.var列是對大數據集

library(data.table) 
dcast(setDT(df1), COMPLAINT ~ SEX, value.var = c("reports", "users")) 
# COMPLAINT reports_F reports_M users_F users_M 
#1: dizziness  12   9 1850 2500 
#2: headache   4   5 3460 1250 
2

How to reshape data from long to wide format?看到相當有效率,我們可以使用library(reshape2)然後

reshape(df, idvar = "COMPLAINT", timevar = "SEX", direction = "wide")

COMPLAINT reports.M users.M reports.F users.F 
1 headache   5 1250   4 3460 
3 dizziness   9 2500  12 1850