I have data.frame
df1
(see code below). I would like to convert it to what df2
looks like (see code below).
Maybe this can be done with reshape
cast
or reverse melt
? But I do not understand these functions. Can anyone help, please?
df1 <- data.frame(
stringsAsFactors = FALSE,
sample = c("a","a","a",
"a","b","c","c","c","c","c","c","c","c",
"d","d","e","e","e","g","g"),
LETTER = c("P","R","V",
"Y","Q","Q","R","S","T","U","W","X","Z",
"Q","X","Q","V","X","Q","T")
)
df2 <- data.frame(
stringsAsFactors = FALSE,
sample = c("a", "b", "c", "d", "e", "f", "g"),
P = c(1L, 0L, 0L, 0L, 0L, 0L, 0L),
Q = c(0L, 1L, 1L, 1L, 1L, 0L, 1L),
R = c(1L, 0L, 1L, 0L, 0L, 0L, 0L),
S = c(0L, 0L, 1L, 0L, 0L, 0L, 0L),
T = c(0L, 0L, 1L, 0L, 0L, 0L, 1L),
U = c(0L, 0L, 1L, 0L, 0L, 0L, 0L),
V = c(1L, 0L, 0L, 0L, 1L, 0L, 0L),
W = c(0L, 0L, 1L, 0L, 0L, 0L, 0L),
X = c(0L, 0L, 1L, 1L, 1L, 0L, 0L),
Y = c(1L, 0L, 0L, 0L, 0L, 0L, 0L),
Z = c(0L, 0L, 1L, 0L, 0L, 0L, 0L)
)
Edit
It was suggested that I look at this post: How to reshape data from long to wide format. Unfortunately, that does not answer my question. The equivalent code would be as follows and throws the following error.
df2 <- reshape(df, idvar = "sample", timevar = "LETTER", direction = "wide")
Error in data[, timevar] : object of type 'closure' is not subsettable
First adding a third variable using df1$value <- 1L
also does not solve it.
Please note that in my data, there is no exact match between length and width of the data, unlike in said post. Any help is still appreciated, please.