2012-09-21 158 views
0

我正在嘗試隔離所有觀察值具有相同值(忽略NAs)的數據幀的那些列。請參閱下面的假設示例:分離具有相同值的列

ForestName <- rep("Planige", 4) 
TreeNumber <- c(1:4) 
Height <- c(2.3, 2, 2.1, 2.9) 
Type <- c("AA", "AA", NA, "AA") 
df <- data.frame(ForestName, TreeNumber, Height, Type) 
df 

新的數據框應該包含ForestName和Type。不同值的列(TreeNumber和Height)應該包含在另一個數據框中。

回答

1

在許多其他的方式,我敢肯定:

df[,sapply(df,function(x) {length(unique(x[!is.na(x)])) > 1})] 

    TreeNumber Height 
1   1 2.3 
2   2 2.0 
3   3 2.1 
4   4 2.9 

你可以否定sapply表達,以獲得其他列。

+0

This作品!謝謝! –

+0

@RobertWest請將正確的解決方案標記爲已接受的答案。 – Superbest

2

可以使用unique並檢查是否這降低到一個單一的元素:

df[sapply(df,function(x) length(unique(x[!is.na(x)])))==1] 
    ForestName Type 
1 Planige AA 
2 Planige AA 
3 Planige <NA> 
4 Planige AA 

或者測試all元素等於所述第一非NA

df[sapply(df, function(x) all(x==na.omit(x)[1],na.rm=T))] 
    ForestName Type 
1 Planige AA 
2 Planige AA 
3 Planige <NA> 
4 Planige AA 
+0

這工作也很好。謝謝! –

0

稍微更緊湊使用相同基本原理的方法

Filter(function(x){length(unique(x[!is.na(x)])) <=1}, df)