0

I have a function:

v0 <- function(n) {
   seq(1:n)
}

and I need to create a function v1 which gives this result:

(1 2 3 -4 -5 -6 7 8 9 -10)            # if n <- 10   or
(1 2 3 -4 -5 -6 7 8 9 -10 -11 -12 13) # if n <- 13 

But I keep getting a warning message when I do:

v1 <- function(n) {
    seq(1:n) * c(1,1,1,-1,-1,-1)
}

Any tips on what is the right way to go about doing this?

coatless
  • 20,011
  • 13
  • 69
  • 84
Eddie Wu
  • 1
  • 2

2 Answers2

0

V0(10) is an array of length 10, while c(1,1,1,-1,-1,-1) has length 6.

The warning that you are getting ("longer object length is not a multiple of shorter object length") is because 6 does not divide 10.

When you do v0(10) * c(1,1,1,-1,-1,-1), R repeats the second array as many times in order to create an array of the same length as v0(10). How? Like this:

v0(10) * c(1,1,1,-1,-1,-1,1,1,1,-1)

If this is not the result you wish to obtain, then either correct v0(10), the second array, or create a function where you define the correct operation between these two arrays.

R. Schifini
  • 9,085
  • 2
  • 26
  • 32
  • Thanks for the help! I see what you mean! I am sorry if i was unclear in my question but it is exactly the function part that I am unable to do. Would really appreciate it if you could offer your help. – Eddie Wu Jan 10 '17 at 07:16
0

You can do something like,

v1 <- function(n){
  t <- seq(1:n)
  t[c(rep(FALSE, 3), rep(TRUE, 3))] <- t[c(rep(FALSE, 3), rep(TRUE, 3))] * (-1)
  return(t)
  }

v1(10)
# [1]   1   2   3  -4  -5  -6   7   8   9 -10

Also have a read at this for more info about the warning

Community
  • 1
  • 1
Sotos
  • 51,121
  • 6
  • 32
  • 66