user2545517
user2545517

Reputation: 89

reshape to wide format when more than two columns

Apologize if this question has been asked before, i didn't find nothing similar. So, it's trivial to reshape when we have something like

id status1 value
1  active   1
2  close    23

result after reshaping will be

id active close
1  1      23

but, what if our table have more than one status column? and we need to reshape by status1, and status2 columns?

id status1 status2 value
1  active  complete 2
2  close   overdue  3

Expecting result

id active close complete overdue

Home the question is clear. Any comments or suggestions will be highly appreciated.

Upvotes: 0

Views: 55

Answers (2)

Hakki
Hakki

Reputation: 1472

Not quite sure what you're after, but maybe this could work.

example:

library(reshape2)

df <- as.data.frame(cbind(c(1,2,3), c("Active", "Close", "Active"),c("one", "two", "one"), c(5,6,7)))
colnames(df) <- c("id", "status1", "status2", "value")

df1 <- dcast(df, id ~ status1)
df2 <- dcast(df, id ~ status2)

merge(df1, df2)

Upvotes: 1

lukeA
lukeA

Reputation: 54287

Here's another option:

library(reshape2)
df <- read.table(header=T, text="id status1 status2 val
1  active  complete 2
2  close   overdue  3")
recast(df, id~value, id.var = c(1, 4), value.var = "val")
#   id active close complete overdue
# 1  1      2    NA        2      NA
# 2  2     NA     3       NA       3

Upvotes: 0

Related Questions