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