0

I'd like to spread my data frame grouped by the TYPE (column 1) to show all the different DESC that are associated with them. I'm working in R; the closest function I can find to handle this situation is tidyr::spread, but I don't want a different column for every single DESC, just counter columns.

Code below creates 2 dataframes that gives an example of what I'd like to convert from and to (mydata -> mydata2)

column1 <- c("color","color","color","size","size")
column2 <- c("red","blue","green","small","big")
mydata <- data.frame(column1,column2)
colnames(mydata)[c(1:2)] <- c("type","desc")
View(mydata)

Convert to:

column1 <- c("color","size")
column2 <- c("red","big")
column3 <- c("green","small")
column4 <- c("blue",NA)
mydata2 <- data.frame(column1,column2,column3,column4)
colnames(mydata2)[c(1:4)] <- c("type","desc1","desc2","desc3","desc4")
View(mydata2)
A Hud
  • 95
  • 7
  • It's not a trivial reshaping IMO, I would do: `mydata$suffix <- ave(1:nrow(mydata),mydata$type,FUN=function(x) 1:length(x)) ` and then `reshape(mydata,direction='wide',idvar='type',timevar='suffix',v.names='desc')` – digEmAll Jun 07 '17 at 13:34
  • 1
    Your desired output doesn't make much sense. You have `blue` in the `size` row. Also, you are passing too many column names to `mydata2`. See if that gives you what you want `library(data.table) ; dcast(setDT(mydata), type ~ rowid(type))` – David Arenburg Jun 07 '17 at 13:51
  • Thanks - this is perfect – A Hud Jun 07 '17 at 13:57
  • David - sorry about that.. I fixed the code – A Hud Jun 07 '17 at 14:00
  • @digEmAll I think there are many dupes for this – akrun Jun 07 '17 at 14:33
  • @akrun yep, jaap has found one perfectly fitting.. My comment was related to the previous selected dupe, which was too basic for this case ;) – digEmAll Jun 07 '17 at 15:19

0 Answers0