Subset dataframe such that all values in each row are less than a certain value

后端 未结 1 837
北荒
北荒 2020-12-12 07:55

I have a dataframe with a dimension column and 4 value columns. How can I subset the column such that all 4 columns for each record are less than a given x? I know I could d

相关标签:
1条回答
  • 2020-12-12 08:19

    You can use the negated rowSums() for the subset

    df[!rowSums(df[-1] > 0.7), ]
    #   zips ABC DEF GHI JKL
    # 4    4 0.6 0.4 0.2 0.3
    # 6    6 0.2 0.7 0.3 0.4
    
    • df[-1] > 0.7 gives us a logical matrix telling us which df[-1] are greater than 0.7
    • rowSums() sums across those rows (each TRUE value is equal to 1, FALSE is zero)
    • ! converts those values to logical and negates them, so that we get any row sums which are zero (FALSE) and turn them into TRUE. In other words, if the rowSums() result is zero, we want those rows.
    • we use that logical vector for the row subset

    Another way to get the same logical vector would be to do

    rowSums(df[-1] > 0.7) == 0
    
    0 讨论(0)
提交回复
热议问题