我正在使用 tidyr 中的 pivot_longer 将数据帧从宽转换为长。我希望使用所有列并在列中维护行名。较早的melt 函数在此调用中完美运行
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 ...
但pivot_longer 没有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')"
任何建议表示赞赏
最佳答案
显然一些数据会有所帮助,但您的问题在于您使用的是 pivot_longer()
在类 matrix
的对象上而不是 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()
将在数据框上工作> class(mycars)
[1] "matrix" "array"
> class(mtcars)
[1] "data.frame"
记得指定 cols
参数,这在 reshape2::melt()
中不是必需的(文档中的更多信息)。你想要所有的列,所以 cols = everything()
:pivot_longer(mtcars, cols = everything())
(免责声明:当然,mtcars
不是转换为长格式的最佳数据集)
关于r - 所有列上的 Pivot_longer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63334436/