1

My aim is to create a vector, with sum 0, in which there are the same number of entries -x and the same number of entry equals x, the length of the vector is even, so it sums up to 0. I created a function, that has x as an input. there i insert a sample of the vectorlength but i the end it doesn't work out.

vector<-function(x){ 
    for(i in length(sample)){
      if(i %% 2!=0){
     output[sample[i]]<-(-x)
   }
    if(i %% 2 ==0){
      output[sample[i]]<-x
    }
  }
return(output)
  }
Roman
  • 17,008
  • 3
  • 36
  • 49
Kasimir
  • 13
  • 4

3 Answers3

0

Try this:

vector <- function(x, sample){
  c(rep(x, sample/2), rep(-x, sample/2))
}
print(vector(x = 1, sample = 4))
# [1]  1  1 -1 -1

Edit

If alterning is required:

vector <- function(x, sample){
    c(rbind(rep(-x, sample/2), rep(x, sample/2)))
}
print(vector(x = 1, sample = 4))
# [1] -1  1 -1  1
ebeneditos
  • 2,542
  • 1
  • 15
  • 35
0

You can try

foo <- function(x, sample){
  a <- sample(sample, x/2, replace = T)
  c(a,-a)
  # or alternating
  # c(rbind(a,-a))
}
set.seed(123)
foo(4, 1:10)
[1]  3  8 -3 -8
Roman
  • 17,008
  • 3
  • 36
  • 49
0

According to the title you are looking for a random vector. In that case you can simply first generate an ordered vector with the desired properties and then use sample to shuffle it:

f <- function(x, size){
  sample(c(rep(x, size/2), rep(-x, size/2), if(size %% 2 != 0) 0))
}
f(x = 1, size = 6)
#> [1]  1 -1 -1  1 -1  1
f(x = 1, size = 7)
#> [1]  0 -1 -1  1 -1  1  1

Edit: Now the function even allows for an odd size.

Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75