删除R中的常量列 [英] Removal of constant columns in R

查看:126
本文介绍了删除R中的常量列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我收到此错误时我正在使用prcomp函数

I was using the prcomp function when I received this error

Error in prcomp.default(x, ...) : 
cannot rescale a constant/zero column to unit variance

我知道我可以扫描我的手动输入数据,但是R中是否有任何函数或命令可以帮助我删除这些常量变量?
我知道这是一个非常简单的任务,但我从未遇到过执行此操作的任何函数。

I know I can scan my data manually but is there any function or command in R that can help me remove these constant variables? I know this is a very simple task, but I have never been across any function that does this.

谢谢,

推荐答案

此处的问题是您的列方差等于零。您可以通过这种方式检查数据帧的哪一列是常量,例如:

The problem here is that your column variance is equal to zero. You can check which column of a data frame is constant this way, for example :

df <- data.frame(x=1:5, y=rep(1,5))
df
#   x y
# 1 1 1
# 2 2 1
# 3 3 1
# 4 4 1
# 5 5 1

# Supply names of columns that have 0 variance
names(df[, sapply(df, function(v) var(v, na.rm=TRUE)==0)])
# [1] "y" 

因此,如果要排除这些列,可以使用:

So if you want to exclude these columns, you can use :

df[,sapply(df, function(v) var(v, na.rm=TRUE)!=0)]

编辑:实际上,使用 apply 更为简单。像这样的东西:

EDIT : In fact it is simpler to use apply instead. Something like this :

df[,apply(df, 2, var, na.rm=TRUE) != 0]

这篇关于删除R中的常量列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆