M.Qasim
M.Qasim

Reputation: 1878

Convert long data frame into wide data frame

I am trying to convert long data form into wide data form in R. For instance, I have following data frame:

a = rep(c("A","B","C","D"),4)
b = rep(c("COL1","COL2","COL3","COL4"),4)
val = 101:116
df = as.data.frame(cbind(a,b,val))
df

I would like to see the result as:

row <- as.list(levels(df$a))
col <- as.list(levels(df$b))

test <- data.frame()

i = 1

  for (j in 1:4) {
    for(k in 1:4){
      test[j,k]  =   df$val[i]
      i = i + 1 
    }
  }

colnames(test) <- c("COL1","COL2","COL3","COL4")
rownames(test) <- c("A","B","C","D")
test

Would appreciate if you could suggest an elegant solution using some handy function. Thanks, Qasim

Upvotes: 3

Views: 1438

Answers (2)

user1600826
user1600826

Reputation:

If your id columns where really unique, you could use reshape

reshape(data=df, direction = "wide", idvar = "a", timevar = "b", v.names = "val")

But as they are not unique, the following will get you on your way.

df$fakeid <- rep(1:4, each=4)
reshape(data=df, direction = "wide", idvar = "fakeid", drop = "a", timevar = "b", v.names = "val")

Upvotes: 3

Arun
Arun

Reputation: 118779

Using unstack:

df.out <- unstack(df, val ~ b)
rownames(df.out) <- unique(df$a)

Using reshape2, it requires a bit of a trick to get an id column, because your identifiers do not uniquely identify the values.

dcast(transform(df, id=rep(1:4, each=4)), id ~ b, value.var="val")

you can then add the row names similarly.

Upvotes: 3

Related Questions