Reputation: 766
I have a dataset like this:
1 2 3 4 5
1 1 0 0 0 0
2 1 0 0 2 0
3 0 0 0 1 5
4 2 0 0 0 0
I want to subset the rows with more than one column beeing non-zero (means rows 2,3)
I know that it has to be something like dataset[... dataset ...] but I did not find out how to access rows as such without using a for-loop
Upvotes: 0
Views: 1430
Reputation: 193687
You just need rowSums
really. Assuming your dataset is called "mydf", try:
> mydf[rowSums(mydf != 0) > 1, ]
X1 X2 X3 X4 X5
2 1 0 0 2 0
3 0 0 0 1 5
Here, rowSums(mydf != 0)
will return a vector of how many values in each row is greater not zero. Then, adding our condition > 1
would create a logical vector which can be used to subset the rows we want.
Upvotes: 2