简体   繁体   中英

R subsetting data according to non zeros in row

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM