Reputation: 167
I am using pivot_longer from tidyr to transform a data frame from wide to long. I wish to use all the columns and maintain rownames in a column as well. The earlier melt function works perfect on this call
w1 <- reshape2::melt(w)
head(w1)
'data.frame': 900 obs. of 3 variables:
$ Var1 : Factor w/ 30 levels "muscle system process",..: 1 2 3 4 5 6 7 8 9 10 ...
$ Var2 : Factor w/ 30 levels "muscle system process",..: 1 1 1 1 1 1 1 1 1 1 ...
$ value: num NA NA NA NA NA NA NA NA NA NA ...
But pivot_longer doesnt
w %>% pivot_longer()
Error in UseMethod("pivot_longer") :
no applicable method for 'pivot_longer' applied to an object of class "c('matrix', 'array', 'double', 'numeric')"
Any suggestion is appreciated
Upvotes: 13
Views: 36188
Reputation: 825
Obviously some data would be helpful, but your problem lies in the fact that you are using pivot_longer()
on an object of class matrix
and not data.frame
library(tidyr)
# your error
mycars <- as.matrix(mtcars)
pivot_longer(mycars)
Error in UseMethod("pivot_longer") :
no applicable method for 'pivot_longer' applied to an object of class
"c('matrix', 'array', 'double', 'numeric')"
pivot_longer()
will work on a data frame
> class(mycars)
[1] "matrix" "array"
> class(mtcars)
[1] "data.frame"
Remember to specify the cols
argument, this was not required in reshape2::melt()
(more info in the documentation). You want all the columns so cols = everything()
:
pivot_longer(mtcars, cols = everything())
(Disclaimer: Of course, mtcars
is not the best dataset to convert to long format)
Upvotes: 25