mapply function not givving proper output

Viewed 21

Was expecting a different output with the code bellow.

vec1 <- c(1, 2, 3, 4)
vec2 <- c(2, 4, 6, 8)
vec3 <- c(3, 6, 9, 12)

printer <- function(val1, val2, val3) {
  print(c (val1, val2,val3))
  }

mapply(printer, vec1, vec2, vec3, SIMPLIFY = T)

Expected:

[1] 1 2 3
[1] 2 4 6
[1] 3 6 9
[1] 4 8 12

Got this instead:

[1] 1 2 3
[1] 2 4 6
[1] 3 6 9
[1]  4  8 12
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    2    4    6    8
[3,]    3    6    9   12

Can anyone please explain why and help me with it????

1 Answers

your actual results can be explained

  1. each printer decides the width of the values its going to print; your 3rd vector has a number spanning 2 positions whereas your other vectors only fit in 1 position, thats why the final printer seems 'dodged'
  2. mapply will not only call the multiple prints but return its own output, hence the matrix at the end

you could so something like the following; control the printing width explicitly, make mapply's own result invisible

vec1 <- c(1, 2, 3, 4)
vec2 <- c(2, 4, 6, 8)
vec3 <- c(3, 6, 9, 12)

printer <- function(val1, val2, val3) {
  cat(format(c (val1, val2,val3),width=2L),"\n")
}

invisible(mapply(printer, vec1, vec2, vec3, SIMPLIFY = T))

Related