You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言数据转置后prcomp报错:数据非数值无明显原因

转置后数据无法用于PCA分析的数值类型问题

问题背景

原有数据分析流程在不转置时正常运行,但因Excel无法容纳29000列变量,只能将变量放在行中,导入R后转置处理,却在执行prcomp时报错,提示数据非数值类型。

核心脚本

library(readxl)
library(tidyverse)
library(factoextra)
library(ggrepel)
library(ggplot2)
library(ggfortify)
library(ggforce)
library(dplyr)
library(data.table)

init <- read_excel("D:/Bureau/Bioinformatique/All_transcripts.xlsx") #Load data

temp <- t(init) #Transpose data as too many columns for excel

temp2 <- data.frame(rownames(temp), temp) #Move row names to the dataframe - to be used later
colnames(temp2) <- temp2[1,] #Set row 1 as columns names
data <- temp2[-1,] #Remove row 1
rownames(data) <- NULL #Transform row names into numbers from 1 to 12

numdata <- data[,-1:-2] #Remove columns 1 and 2, which are group names and not numeric values
numdata <- lapply(numdata, as.numeric) #Set everything as numeric values

prcomp(numdata, scale. = TRUE, center = TRUE)
pca<-prcomp(numdata, scale. = TRUE, center = TRUE)

报错细节

str(numdata)
List of 29701
$ ENST00000000233_10: num [1:12] 2 7 6 9 5 23 2 5 8 8 ...
$ ENST00000000412_8 : num [1:12] 1 2 1 1 0 1 0 0 1 1 ...
$ ENST00000001008_6 : num [1:12] 0 1 0 0 0 0 0 0 1 0 ...
...

is.numeric(numdata)
[1] FALSE

prcomp(numdata, scale. = TRUE, center = TRUE)
Erreur dans colMeans(x, na.rm = TRUE) : 'x' doit être numérique
# 翻译:Error in colMeans(x, na.rm = TRUE) : 'x' must be numerical

问题核心:lapply(numdata, as.numeric)返回的是列表,而prcomp要求输入为数值型矩阵或数据框,列表无法被识别为合法的数值输入。


解决方案

方案1:将列表转换为数值型数据框

把lapply的结果转换为数据框,确保输入格式符合prcomp要求:

numdata <- data[,-1:-2]
# 转成数值型数据框(替代原lapply仅返回列表的操作)
numdata <- as.data.frame(lapply(numdata, as.numeric))
# 或用dplyr更简洁的写法:
numdata <- data[,-1:-2] %>% mutate_all(as.numeric)

# 执行PCA
pca <- prcomp(numdata, scale. = TRUE, center = TRUE)

方案2:优化转置流程(适配大样本,避免类型混乱)

转置data.frame容易触发类型自动转换,建议先转为矩阵再转置,从根源避免类型问题:

init <- read_excel("D:/Bureau/Bioinformatique/All_transcripts.xlsx")

# 先将数据转为矩阵(假设第一列是变量名,后续列为数值)
init_mat <- as.matrix(init[, -1])
rownames(init_mat) <- init[, 1]

# 转置矩阵,此时行对应样本,列对应变量
temp_mat <- t(init_mat)

# 转为数据框,如需分组信息可手动添加
data <- as.data.frame(temp_mat)
# data$group <- ... # 按需从原始数据提取分组列

# 直接执行PCA,矩阵已为数值型
pca <- prcomp(data, scale. = TRUE, center = TRUE)

方案3:用data.table高效处理大数据

针对29000列的大数据集,data.table处理速度更优:

init <- fread("D:/Bureau/Bioinformatique/All_transcripts.xlsx") # 更快的读取方式
# 转置并处理列名
temp <- transpose(init, keep.names = "var_name")
colnames(temp) <- temp[1, ]
temp <- temp[-1, ]
# 转换数值列
numdata <- temp[, -1:-2] %>% mutate_all(as.numeric)
# 执行PCA
pca <- prcomp(numdata, scale. = TRUE, center = TRUE)

关键说明

  • 转置data.frame时,R会自动将混合类型列转为字符型,这是转置后需手动转换类型的根本原因。
  • is.numeric()对列表返回FALSE是正常行为,因为列表不是单一数值向量,需转换为数据框/矩阵后再验证数值类型。

内容的提问来源于stack exchange,提问作者Thibault

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:40:34