如何使用 Melt 函数重新排列给定数据

how to use Melt function to rearrange a given data

我在这里尝试使用以下功能http://www.r-bloggers.com/using-r-two-plots-of-principal-component-analysis/

我的做法如下:

data(iris) 
df <- iris[,1:4]
variable.groups <- c(rep(1,50), rep(2,50), rep(3,50))
library(reshape2)
library(ggplot2)
pca <- prcomp(df, scale=TRUE)
melted <- cbind(variable.groups, melt(pca$rotation[,1:4]))

我收到一条错误消息

Error in data.frame (..., check.names=FALSE): arguments imply differing number of rows: 150, 16 

我基本上不明白的是,上面的熔化是什么link,有什么想法,我如何才能将虹膜数据设置为相同?

快速回答:

variable.groups 需要长度为 4。所以这修复了它:

variable.groups <- c(1,2,3,4) #or any other 4 classes

长答案:

将您的代码与 http://www.r-bloggers.com/using-r-two-plots-of-principal-component-analysis/ 处的代码进行比较,我认为您将 sample.groupsvariable.groups 混在一起了。

从那里的文章中获取 data 它具有以下尺寸:

> dim(data)
[1] 50 70

因此 sample.groupsvariable.groups 确实具有以下长度:

> length(sample.groups)
[1] 50
> length(variable.groups)
[1] 70

在您的代码中,dfvariable.group 确实具有以下维度:

> dim(df)
[1] 150   4
> length(variable.groups)
[1] 150

因此,与您引用的代码相比,您的 variable.groups 长度应该为 4。