Convert long data frame into wide data frame

泄露秘密 提交于 2019-12-07 13:24:42

问题


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


回答1:


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")



回答2:


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.



来源:https://stackoverflow.com/questions/16143441/convert-long-data-frame-into-wide-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!