2017-01-17 4 views
1

Können Sie eine elegantere Lösung für das folgende Problem vorschlagen? Entfernen Sie Zeilen mit mehr als einer 0 in den Spalten x, z, y oder a, b, c.Mehrere Untergruppen

df <- data.frame(x = 0, y = 1:5, z = 0:4, a = 4:0, b = 1:5, c=0) 

meine Lösung

df_new <- subset(df, ((((x != 0 & y != 0) | (x != 0 & z != 0) | (y != 0 & z != 0)) & ((a != 0 & b != 0) | (a != 0 & c != 0) | (b != 0 & c != 0))))) 
(Zeile 1 und Zeile 5 sollte entfernt werden)

Antwort

1
# 1:3 is same as columns 'x', 'y', 'z', Similarily for 4:6 . 
# You can also specify the colnames explicitly 
# add a na.rm = T inside rowSums() incase you also have missing data 
(rowSums(df[, 1:3]==0)>1)|(rowSums(df[, 4:6]==0)>1) 

# did you mean this ? 
df[!((rowSums(df[, 1:3]==0)>1)|(rowSums(df[, 4:6]==0)>1)),] 
# x y z a b c 
#2 0 2 1 3 2 0 
#3 0 3 2 2 3 0 
#4 0 4 3 1 4 0 
Verwandte Themen