Reputation: 3330
Hey guys I'm pretty new to R so apologies if this is a dumb question. I have a data frame that looks like this:
Gelatin Geltrex Combo Control
1 0.761 0.732 0.557 0.723
2 0.704 0.712 0.764 0.540
3 0.580 0.435 0.351 0.537
I want to end up with 2 columns; one with the numbers in the row and another column with the current column names as identifiers for the numbers?
Upvotes: 4
Views: 6587
Reputation: 39
Maybe you can use gather from the tidyr package
> library(tidyr)
> df = data.frame(a = c(1,2,3), b = c(4,5,6), d = c(7, 8, 9))
> newdf = gather(df, columnNames, values)
columnNames values
1 a 1
2 a 2
3 a 3
4 b 4
5 b 5
6 b 6
7 d 7
8 d 8
9 d 9
Upvotes: 1
Reputation: 886948
If we need row/column index we can use row
and col
to get the row/column index and create a new dataset with data.frame
.
df2 <- data.frame(Row= c(row(df1)),
Col=names(df1)[col(df1)], stringsAsFactors=FALSE)
Or another option is melt
from library(reshape2)
. We convert the 'data.frame' to 'matrix' and melt
to get the row/column names as the first two columns.
library(reshape2)
melt(as.matrix(df1))[-3]
EDIT:
If we need the value
and column names as the two columns, just melt
or use stack
as @thelatemail mentioned
melt(df1)
Or stack
from base R
stack(df1)
Upvotes: 5