JKJ
JKJ

Reputation: 212

Averaging random elements of a vector in R

I have a list lets say of 4 items, I need to cut down that list to 2 by taking any two elements of that list and finding the average of that list. This is the algorithm I came up with, I do not know how to write this in R.

  1. choose an x_i
  2. choose an x_j not equal to x_i
  3. find the average of x_i and x_j
  4. choose a new x_(i+1) and x_(j+1) as long as they are not equal to x_i or x_j

for example:

x <- c(2,4,6,8)
y <- c((2+4)/2,(6+8)/2) or c((2+6)/2,(2+8)/2) or anything similar to that.

Upvotes: 0

Views: 86

Answers (1)

tblznbits
tblznbits

Reputation: 6778

For the sake of closing this question as answered, we can use the following syntax to do what we need to do: replicate(2, mean(sample(x, 2)))

Upvotes: 1

Related Questions