2016-07-22 17 views
1

我有一個像功能進行測試,如果在數據幀中的一行不包含給定元素

a <- c(2, 3, 4) 
b <- c(5, 4, 3) 
c <- c(2, 7, 9) 
df <- data.frame(a, b, c) 

df 
# a b c 
# 1 2 5 2 
# 2 3 4 7 
# 3 4 3 9 

一個數據幀,我想找回的行數不2,在我的例子,這只是第二行。

+2

你的意思是輸出應該是第2和第3行? – zx8754

+0

你的解決方案是爲列,我想有一個不包含2的數據框的行,在例子中的第二行。 – hsteini

回答

3

使用rowSums或colSums:

# data 
a <- c(2, 3, 4) 
b <- c(5, 4, 3) 
c <- c(2, 7, 9) 
df <- data.frame(a, b, c) 

df 
# a b c 
# 1 2 5 2 
# 2 3 4 7 
# 3 4 3 9 


# get rows with no 2 
df[ rowSums(df == 2, na.rm = TRUE) == 0, ] 
# a b c 
# 2 3 4 7 
# 3 4 3 9 

# get columns with no 2 
df[ , colSums(df == 2, na.rm = TRUE) == 0, drop = FALSE ] 
# b 
# 1 5 
# 2 4 
# 3 3 
2

我們也可以使用Reduce==得到行

df[!Reduce(`|`, lapply(df, `==`, 2)),] 
# a b c 
#2 3 4 7 
#3 4 3 9 

anylapply選擇列

df[!sapply(df, function(x) any(x== 2))] 
# b 
#1 5 
#2 4 
#3 3 
1

這裏是我使用一些設置功能的解決方案。首先,這兩個位置在哪裏?

is_two <- apply(df, 1, is.element, 2) 

     [,1] [,2] [,3] 
[1,] TRUE FALSE FALSE 
[2,] FALSE FALSE FALSE 
[3,] TRUE FALSE FALSE 

現在,哪些行都是FALSE?

no_twos <- apply(!is_two, 1, all) 
df[no_twos,] 
a b c 
2 3 4 7 
相關問題