本文介绍了从数据框中删除具有相同值的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数据框
I've got a data frame like this one
1 1 1 K 1 K K
2 1 2 K 1 K K
3 8 3 K 1 K K
4 8 2 K 1 K K
1 1 1 K 1 K K
2 1 2 K 1 K K
我想删除所有具有相同值(即K)的列,所以我的结果将是这样
I want to remove all the columns with the same value, i.e K, so my result will be like this
1 1 1 1
2 1 2 1
3 8 3 1
4 8 2 1
1 1 1 1
2 1 2 1
我尝试在for by列中进行迭代,但没有得到任何结果.有什么想法吗?
I try to iterate in a for by columns but I didn't get anything. Any ideas?
推荐答案
要选择具有多个值的列,而与类型无关:
To select columns with more than one value regardless of type:
uniquelength <- sapply(d,function(x) length(unique(x)))
d <- subset(d, select=uniquelength>1)
?
(糟糕,Roman的问题是对的-这也可能使您的第5栏消失)
(Oops, Roman's question is right -- this could knock out your column 5 as well)
也许(编辑:感谢评论!)
isfac <- sapply(d,inherits,"factor")
d <- subset(d,select=!isfac | uniquelength>1)
或
d <- d[,!isfac | uniquelength>1]
这篇关于从数据框中删除具有相同值的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!