2017-08-04 62 views
0

新的數據列使用下面的數據:創建與發生變異

data <- data.frame(Name=c("11C","11C","12C","12C","20D","20D"), 
       PID=c("AD15E","AD15E","AA05D","AA05D","Z48J","Z48J"), 
       Type=c("Home","Auto","Home","Auto","Home","Auto"), 
       Brand=c("A","B","C","H","I","D"), 
       Model=c("A152","K235","W54","H2","A57","Y0878")) 

使用變異,我想在數據幀(HomeBrand,HomeModel,AutoBrand,AutoModel)在該行建立4個新列,其中第一唯一PID顯示。

結果應該如下所示:

result <- data.frame(Name=c("11C","12C","20D"), 
       PID=c("AD15E","AA05D","Z48J"), 
       Type=c("Home","Home","Home"), 
       HomeBrand=c("A","C","I"), 
       HomeModel=c("A152","W54","A57"), 
       AutoBrand=c("B","H","D"), 
       AutoModel=c("K235","H2","Y0878")) 

我一直在使用發生變異嘗試,但似乎無法弄清楚

回答

3

它沒有意義的,有類型首頁中的結果因爲類型列轉到頁眉,並且對於每一行你有混合首頁自動值;如果沒有此列,它是一個簡單的任務與reshape

reshape(data, idvar = c("Name", "PID"), timevar = "Type", direction = "wide") 

# Name PID Brand.Home Model.Home Brand.Auto Model.Auto 
#1 11C AD15E   A  A152   B  K235 
#3 12C AA05D   C  W54   H   H2 
#5 20D Z48J   I  A57   D  Y0878 

爲了便於比較,這是你的結果:

result 
# Name PID Type HomeBrand HomeModel AutoBrand AutoModel 
#1 11C AD15E Home   A  A152   B  K235 
#2 12C AA05D Home   C  W54   H  H2 
#3 20D Z48J Home   I  A57   D  Y0878 
0

我們可以做到這一點dcast

library(data.table) 
dcast(setDT(data), Name + PID ~ Type, value.var = c("Brand", "Model"), sep="") 
# Name PID BrandAuto BrandHome ModelAuto ModelHome 
#1: 11C AD15E   B   A  K235  A152 
#2: 12C AA05D   H   C  H2  W54 
#3: 20D Z48J   D   I  Y0878  A57 
相關問題