Filter a vector based on another vector

24 Views Asked by At

I am trying to do something in R and it doesn't quite work, so I wanted to once more ask for advice here. I think the issue has to do with filtering a dataframe vs. filtering a vector, and I find posts related to my issue but not close enough for me to adapt the proposed solution to my problem.

I have a cross-national survey dataset, and I want to generate a vector that contains the means of the responses to a survey question, filtered by country. The country is given by a factor variable in the dataset. Basically, imagine a question "how many apples do you eat per day?" asked to people in two countries. I now want a vector consisting of the mean value for countries A and B.

To simulate:

y <- c(1,2,3,4,5,6)
z <- c("BE", "BE", "BE", "NL", "NL", "NL")

I now want a vector with two values, the average value of apples eaten by the Belgian respondents and the same for the Dutch respondents.

I tried something similar to this:

x <- c(mean(filter(data$dailyapples, z == 'BE')), mean(filter(data$dailyapples, z == 'NL')

But it gives me this error:

Error in UseMethod("filter") : 
  no applicable method for 'filter' applied to an object of class "c('double', 'numeric')"

As I said, I think it has something to do with filtering vectors vs. filtering dataframes, but that doesn't solve the issue yet. If anyone can help me, and ideally also explain briefly why filter doesn't work, it'd be much appreciated!

0

There are 0 best solutions below