bm1125
bm1125

Reputation: 223

Error when trying to calculate column average - R

I have a dataframe so when I try to calculate the mean of column A I just write

mean(df$A)

and it works fine.

But when I try to calculate mean of only part of the data frame I get an error saying it isn't a number or logical value

df$A %>% filter(A=="some value") %>% mean(df$A) 

The type of A is double. I also tried to convert it to numeric using

df$A <- as.numeric(as.character(df$A))

but it didn't work.

Upvotes: 0

Views: 96

Answers (2)

AleBdC
AleBdC

Reputation: 81

Best would be to provide an example of your column A.

However, by just looking to your question the problem is in your magrittr-dplyr syntax.

base syntax:

mean(df$A[df$A == 'some value'])

dplyr with pipes:

df %>% filter(A==2) %>% summarise(., average = mean(A))

Careful with syntax and pipes, more info here.

Upvotes: 2

nghauran
nghauran

Reputation: 6778

Try df %>% filter(A==some value) %>% summarise(mean(A)).

Note that the mean will be some value because of the filter. Also, mean() works fine with objects of class double

Upvotes: 1

Related Questions