-1

I have a data frame with this format:

df
name,status,text
stock1,open,text1 
stock1,closed,text something here

and I would like to convert it like this:

name,status1,status2,text1,text2
stock1,open,closed,text1,text something here

How can I convert its columns to rows without know the exact number of columns?

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Berbery
  • 297
  • 2
  • 4
  • 12

1 Answers1

1

We can use dcast from library(data.table) which can take multiple value.var columns.

We convert the 'data.frame' to 'data.table' (setDT(df1)), grouped by 'name', we create a sequence column ('N'), then use dcast and specify the value.var columns.

library(data.table)
setDT(df1)[, N:= 1:.N, name]
dcast(df1, name~N, value.var=c("status", "text"))
#    name status_1 status_2 text_1              text_2
#1: stock1     open   closed text1  text something here

Or a base R option is reshape after creating a sequence column by "name".

df2 <- transform(df1, N= ave(seq_along(name), name, FUN=seq_along))
reshape(df2, idvar="name", timevar="N",direction="wide")
#   name status.1 text.1 status.2              text.2
#1 stock1     open text1    closed text something here

data

df1 <- structure(list(name = c("stock1", "stock1"), 
status = c("open", 
"closed"), text = c("text1 ", "text something here")), 
.Names = c("name", 
"status", "text"), class = "data.frame",
 row.names = c(NA, -2L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you. It is perfect for me! Just an additional question if I have more value like a name stock2 but it is not contains for example the status could be possible to add NA values with d cast or should I add something? – Berbery Jan 10 '16 at 20:54
  • 1
    @Berbery If it doesn't have any value, the `dcast` should fill it by `NA` as default or you can specify the `fill=` argument – akrun Jan 10 '16 at 20:55