Delete rows in R if a cell contains a value larger than x

后端 未结 1 1635
有刺的猬
有刺的猬 2021-01-18 12:55

I want to delete all rows containing a value larger than 7 in a cell in an arbitrary column, either across all columns or across specific columns.



        
相关标签:
1条回答
  • 2021-01-18 13:17

    rowSums of the logical matrix df > 7 gives the number of 'TRUE' per each row. We get '0' if there are no 'TRUE' for that particular row. By negating the results, '0' will change to 'TRUE", and all other values not equal to 0 will be FALSE. This can be used for subsetting.

    df[!rowSums(df >7),]
    #  a b c
    #2 6 6 5
    #4 7 4 7
    

    For the 'V2', we use the same principle except that we are getting the logical matrix on a subset of 'df'. ie. selecting only the second and third columns.

    df[!rowSums(df[-1] >7),]
    #   a b c
    #2  6 6 5
    #3 99 3 6
    #4  7 4 7
    #6  9 6 3
    
    0 讨论(0)
提交回复
热议问题