我正在将R princomp用于PCA,但是,我有一个具有因子变量的数据集,我想对每个因子运行princomp。
这可以在SAS中使用“ BY”语句来完成,该语句“ 执行BY组处理,这使您可以对分组的观察值进行单独的分析”(来自https://support.sas.com/rnd/app/stat/procedures/princomp.html)
可以通过R中的princomp完成此操作,还是必须将我的数据分成几个数据集并在每个数据集上运行princomp?
祝一切顺利,
一旦您了解列表的工作原理,它在R中非常简单。为此,您应该花一些时间阅读R教程,其中包括对列表的讨论。使用R上可用的数据集:
data(iris)
str(iris)
# 'data.frame': 150 obs. of 5 variables:
# $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
[首先将数据帧分成3个单独的数据帧,每个物种一个,并将它们存储在列表中。我们将省略“种类”标签,因为它不会在主要成分中使用,然后在每个组上运行分析:
iris.spl <- split(iris[, 1:4], iris$Species)
iris.spl.pca <- lapply(iris.spl, prcomp, scale.=TRUE)
要在列表中的每个数据框中保留Species
,您将使用以下代码:
iris.spl <- split(iris, iris$Species)
iris.spl.pca <- lapply(iris.spl, function(x) prcomp(x[, 1:4], scale.=TRUE))
获得基本结果:
iris.spl.pca
要获得特定结果,请使用:
iris.spl.pca[[1]] # or iris.spl.pca[["setosa"]]
我根据手册页面[Details]部分中prcomp
的建议使用princomp
。使用scale.=TRUE
分析相关矩阵,将其删除将分析协方差矩阵。