我想将我的一个列值转换为R中的多个变量

时间:2017-05-23 06:33:46

标签: r

我有以下格式的数据

ID  ID_2    Item ID
001 111 1111
001 111 1112
001 112 1113
001 112 1114
001 112 1115
001 112 1116
001 113 1117
008 222 1118
008 222 1119
008 223 1120
011 333 1121
012 444 1122
012 444 1123
012 444 1124
012 444 1125
012 444 1126
017 555 1127
017 555 1128
017 555 1129

但我想根据它们在ID_2和ID_1中出现的顺序将item_ID转换为多个变量。有点像我在下面提到的那样

ID  ID_2    Item_1  Item_2  Item_3  Item_4  Item_5
001 111 1111    1112            
001 112 1113    1114    1115    1116    
001 113 1117                
008 222 1118    1119            
008 223 1120                
011 333 1121                
012 444 1122    1123    1124    1125    1126
017 555 1127    1128    1129        

我尝试过连接ID和ID_2,然后创建一个密钥号1,2 ..这样一旦Concatenated值改变,密钥就会改变。但我继续保持38L数据行。

我很感激之前处理过类似问题的人的任何帮助。谢谢

3 个答案:

答案 0 :(得分:1)

使用dplyrtidyr个包:

dat %>% 
    group_by(ID, ID_2) %>% 
    mutate(item = paste0("Item_", 1:n())) %>% 
    spread(item, Item_ID)

Source: local data frame [8 x 7]
Groups: ID, ID_2 [8]

     ID  ID_2 Item_1 Item_2 Item_3 Item_4 Item_5
* <int> <int>  <int>  <int>  <int>  <int>  <int>
1     1   111   1111   1112     NA     NA     NA
2     1   112   1113   1114   1115   1116     NA
3     1   113   1117     NA     NA     NA     NA
4     8   222   1118   1119     NA     NA     NA
5     8   223   1120     NA     NA     NA     NA
6    11   333   1121     NA     NA     NA     NA
7    12   444   1122   1123   1124   1125   1126
8    17   555   1127   1128   1129     NA     NA

答案 1 :(得分:1)

我们可以使用dcast

中的data.table
library(data.table)
dcast(setDT(df1), ID + ID_2 ~ paste0("Item_", rowid(ID, ID_2)), value.var = "ItemID")
#    ID ID_2 Item_1 Item_2 Item_3 Item_4 Item_5
#1:  1  111   1111   1112     NA     NA     NA
#2:  1  112   1113   1114   1115   1116     NA
#3:  1  113   1117     NA     NA     NA     NA
#4:  8  222   1118   1119     NA     NA     NA
#5:  8  223   1120     NA     NA     NA     NA
#6: 11  333   1121     NA     NA     NA     NA
#7: 12  444   1122   1123   1124   1125   1126
#8: 17  555   1127   1128   1129     NA     NA

答案 2 :(得分:1)

使用str_split_fixed库中的str_countstringr可能会有以下几点:

library("stringr")

df1<- aggregate( Item_ID ~ ID_2 + ID ,data=df,paste0,collapse =",")
maxl <- max(str_count(df1$Item_ID,","))+1
splitcols <- str_split_fixed(df1$Item_ID,pattern=",",n=maxl)
setNames(data.frame(df1[,2:1],splitcols),c("ID","ID_2",paste0("Item_",1:maxl)))

<强>输出

#    ID ID_2 Item_1 Item_2 Item_3 Item_4 Item_5
# 1  1  111   1111   1112                     
# 2  1  112   1113   1114   1115   1116       
# 3  1  113   1117                            
# 4  8  222   1118   1119                     
# 5  8  223   1120                            
# 6 11  333   1121                            
# 7 12  444   1122   1123   1124   1125   1126
# 8 17  555   1127   1128   1129              
# >