-2

My R vector looks like this:

vector <- c(3, 2, 1, 4, 6, 2, 7)

I want to use the function tapply() to calculate the mean of the first 4 number from the vector. How do I do it?

What did I do?

tapply(vector(1,4), mean)

but it seems like it does not work this way.

We need to use tapply() function.

floss
  • 2,603
  • 2
  • 20
  • 37
  • @thelatemail my question requires `tapply()` but the `duplicate` you marked does not use `tapply()` – floss Oct 02 '19 at 00:19
  • I didn't downvote but you should include the expected output. I assume ```2.5``` but your insistance on ```tapply()``` makes me question that assumption. Also, what do you get when you run ```vector(1,4)```? – Cole Oct 02 '19 at 00:37
  • @Cole I get this error: `Error in unique.default(x, nmax = nmax) : unique() applies only to vectors` but I figured out the solution and `answered it below`. – floss Oct 02 '19 at 05:04
  • `Solution: ` First categorize it. `temp_vector = c(1,1,1,1,2,2,2)` and then `tapply(vector, temp_vector, mean)` which will give you `2.5, 5.0`. Exactly the answer I was looking for. – floss Oct 02 '19 at 05:07

1 Answers1

1

You can simply do

mean(vector[1:4])
fmarm
  • 4,209
  • 1
  • 17
  • 29