Search code examples
rerror-handlingmeantibble

cannot compute conditionated mean


I have this small dataset

structure(list(score = c("mine_score", "your_score", "mine_score", 
                            "your_score", "mine_score", "your_score"), points = c(53, 13.25, 
                                                                               17.5, 1.59090909090909, 48.5, 6.92857142857143)), row.names = c(NA, 
                                                                                                                                               -6L), class = c("tbl_df", "tbl", "data.frame"))

and when applying this formula:

mean(long[long$score == 'mine_score', "points"], na.rm = TRUE)

I got this error, but cannot figure out why:

Warning message:
In mean.default(long[long$score == "mine_score", "points"], na.rm = TRUE) :
  the argument is not numeric or logic: returns NA

Could anyone possibly know what this error is due to? Thanks


Solution

  • Your query is returning a one-column dataframe, which mean does not understand; it has to return a vector. You can use $ to return a vector:

    mean(long$points[long$score == 'mine_score'], na.rm = TRUE)
    #[1] 39.66667
    

    If you really want to stick with your original query, you can use [[1]] to return the first column of your dataframe as a vector:

    mean(long[long$score == 'mine_score', "points"][[1]], na.rm = TRUE)