繁体   English   中英

运行因子加载后,如何在 r 中的 pca 分析中保持 id 变量?

[英]How do I keep id variable in pca analysis in r after running factor loadings?

我正在尝试使用以下数据集通过 r 中的主成分分析 (pca) 运行社会资本数据: https : //aese.psu.edu/nercrd/community/social-capital-resources/social-capital-variables- for-2014/social-capital-variables-spreadsheet-for-2014/view

我的分析运行得很好,但我需要将因子载荷合并到原始数据集上以进行进一步的分析和展示。 我只需要知道在运行 pca 分析时如何保留 id 变量,以便将它们合并到原始数据集上。

我已经标准化了数据,然后运行下面的代码(我从另一个来源收集)。 我在美国每个县的一列中收到似乎是因子载荷,但我的问题是我的原始数据库包含每个县的 id 变量(FIPS 代码),但因子载荷没有。

calcpc <- function(variables,loadings)
{
  # find the number of samples in the data set
  as.data.frame(variables)
  numsamples <- nrow(variables)
  # make a vector to store the component
  pc <- numeric(numsamples)
  # find the number of variables
  numvariables <- length(variables)
  # calculate the value of the component for each sample
  for (i in 1:numsamples)
  {
    valuei <- 0
    for (j in 1:numvariables)
    {
      valueij <- variables[i,j]
      loadingj <- loadings[j]
      valuei <- valuei + (valueij * loadingj)
    }
    pc[i] <- valuei
  }
  return(pc)
}
xxx<-calcpc(standardisedconcentrations, socialcapital.pca$rotation[,1])

假设您将socialcapital.pca计算为
socialcapital.pca <- prcomp(standardisedconcentrations)

并且standardisedconcentrations等于标准化的分析变量,它们在分析数据集中出现的顺序相同,然后您可以简单地将 FIPS 代码(作为另一列或作为行名称)附加到由calcpc()函数创建的输出 PC 向量,因为主成分分数中的行顺序与原始数据中的行顺序相同。

另外,请注意两点:

  1. 您可以避免calcpc()函数内的两个循环,并通过使用以下矩阵计算来计算 PC 向量来加快进程:
    pc <- variables %*% loadings
    假设您将calcpc()函数调用为:
    calcpc(standardisedconcentrations, socialcapital.pca$rotation[,1,drop=FALSE])
    我添加了drop=FALSE以确保rotation属性的第一列保留为具有一列的矩阵。
  2. 如果您调用princomp()函数而不是prcomp()函数来运行主成分分析,则会直接获得主成分或分数作为输出对象的一部分(在属性scores )。
    您只需要了解使用princomp()prcomp()运行 PCA 的差异,主要是引用文档:
    princomp: “请注意,默认计算使用协方差矩阵的除数 N。”
    prcomp: “与 princomp 不同,方差是用通常的除数 N - 1 计算的。”

编辑:如下面的评论所示,您还可以将分析矩阵或数据框的 rownames 属性设置为数据中的FIPS变量,并且由princomp()prcomp()完成的分析结果将包含这些 ID行名称。
例如:使用princomp()

rownames(standardisedconcentrations) <- FIPS
socialcapital.pca <- princomp(standardisedconcentrations)

然后主成分矩阵socialcapital.pca$scores的行名称将包含FIPS代码。

或者使用prcomp()

rownames(standardisedconcentrations) <- FIPS
socialcapital.pca <- prcomp(standardisedconcentrations)
pc1 <- standardisedconcentrations %*% socialcapital.pca$rotation[,1]

然后pc1的行名称将包含FIPS代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM