-2

How can one reshape data-frame like this:

x1  x2  x3  x4
1   1   5   6
1   2   3   5
2   1   6   1
2   2   2   4

to:

x1  1   
x1  1
x1  2
x1  2
x2  1
.
.
.

I have read many posts (like this one) but I could not figure this out.

Arthur
  • 1,208
  • 13
  • 25
nik
  • 2,500
  • 5
  • 21
  • 48
  • 1
    `data.frame(nm = rep(names(df), each = nrow(df)), value = unlist(df), row.names = NULL)` – d.b Oct 31 '17 at 16:06
  • This questions is not useful. You said "I have read many posts but I could not figure this out" but a simple "R + reshape" search on this website brings on this page: https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format, which I assume contains your answer. (And if it does not, you have to explain why.) – Arthur Oct 31 '17 at 16:21
  • 2
    Possible duplicate of [How to reshape data from long to wide format?](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format) – Arthur Oct 31 '17 at 16:25
  • @Arthur this is not unstacking problem. thanks for that post but not really useful – nik Oct 31 '17 at 16:36
  • OK, and sorry for being rude. Maybe the title of your question is misleading... – Arthur Oct 31 '17 at 16:37
  • @Arthur you can always modify the title and the question. I am always happy to learn and I appreciate the time you have put and looked at my question. Thanks – nik Oct 31 '17 at 16:40

2 Answers2

2

By using stack

stack(df)
   values ind
1       1  x1
2       1  x1
3       2  x1
4       2  x1
5       1  x2
6       2  x2
7       1  x2
8       2  x2
9       5  x3
10      3  x3
11      6  x3
12      2  x3
13      6  x4
14      5  x4
15      1  x4
16      4  x4

For plot

df$ind=as.character(df$ind)
boxplot(values~ind,data=df)
BENY
  • 317,841
  • 20
  • 164
  • 234
1

Using the melt() command would likely be the best solution assuming you've got an ID column as well. Check out this link for a further explanation.

newdf <- reshape2::melt(df, id="id").

If you don't have an ID already you can make rownames an ID column and then drop it later.

df$id <- rownames(df)
newdf <- melt(df, id="id").
newdf$id <- NULL

Also, it's bad form to ask further questions in the comments but run ?boxplot() in the console and it should be fairly straightforward.

d.b
  • 32,245
  • 6
  • 36
  • 77
cparmstrong
  • 799
  • 6
  • 23