There are a couple of problems here:
- You're actually using the "reshape" package, not "reshape2".
- You're specifying a vector of values as the "id" variable, hence this warning.
Consider the following:
long <- structure(list(ID = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("A",
"B", "C"), class = "factor"), variable = structure(c(1L, 1L,
1L, 2L, 2L, 2L), .Label = c("V1", "V2"), class = "factor"), value = 1:6),
.Names = c("ID", "variable", "value"), row.names = c(NA, 6L), class = "data.frame")
Using cast
from "reshape" gives you something that looks like a data.frame
, but which has a bunch of other attributes.
reshape_df <- reshape::cast(long, ID ~ variable)
str(reshape_df)
# List of 3
# $ ID: Factor w/ 3 levels "A","B","C": 1 2 3
# $ V1: int [1:3] 1 2 3
# $ V2: int [1:3] 4 5 6
# - attr(*, "row.names")= int [1:3] 1 2 3
# - attr(*, "idvars")= chr "ID"
# - attr(*, "rdimnames")=List of 2
# ..$ :'data.frame': 3 obs. of 1 variable:
# .. ..$ ID: Factor w/ 3 levels "A","B","C": 1 2 3
# ..$ :'data.frame': 2 obs. of 1 variable:
# .. ..$ variable: Factor w/ 2 levels "V1","V2": 1 2
Here's your warning
:
reshape::melt(reshape_df, reshape_df$ID)
# ID value variable
# V1 A 1 V1
# V1.1 B 2 V1
# V1.2 C 3 V1
# V2 A 4 V2
# V2.1 B 5 V2
# V2.2 C 6 V2
# Warning message:
# In if (drop.margins) { :
# the condition has length > 1 and only the first element will be used
And the same thing, without a warning
.
reshape::melt(reshape_df, id = "ID")
# ID value variable
# V1 A 1 V1
# V1.1 B 2 V1
# V1.2 C 3 V1
# V2 A 4 V2
# V2.1 B 5 V2
# V2.2 C 6 V2
A better approach would be to stop using "reshape" and start using "reshape2", "data.table" (which provides more flexible implementations of melt
and dcast
than "reshape2" does), or "tidyr".
Here's the same set of steps with "reshape2":
reshape2_df <- reshape2::dcast(long, ID ~ variable)
You get back a standard data.frame
with no extra attributes.
str(reshape2_df)
# 'data.frame': 3 obs. of 3 variables:
# $ ID: Factor w/ 3 levels "A","B","C": 1 2 3
# $ V1: int 1 2 3
# $ V2: int 4 5 6
melt
ing is not a problem either -- just don't supply it with a vector, as you did in your attempt.
reshape2::melt(reshape2_df, "ID")
# ID variable value
# 1 A V1 1
# 2 B V1 2
# 3 C V1 3
# 4 A V2 4
# 5 B V2 5
# 6 C V2 6