r - odd behavior of print within mapply -
i seeing unexpected behavior (to me anyway) when print()
included side effect in function wrapped in mapply()
.
for example, works expected (and yes know it's not how add vectors):
mapply(function(i,j) i+j, i=1:3, j=4:6) # returns [1] 5 7 9
and this:
mapply(function(i,j) paste(i, "plus", j, "equals", i+j), i=1:3, j=4:6) # returns [1] "1 plus 4 equals 5" "2 plus 5 equals 7" "3 plus 6 equals 9"
but doesn't:
mapply(function(i,j) print(paste(i, "plus", j, "equals", i+j)), i=1:3, j=4:6) # returns: # [1] "1 plus 4 equals 5" # [1] "2 plus 5 equals 7" # [1] "3 plus 6 equals 9" # [1] "1 plus 4 equals 5" "2 plus 5 equals 7" "3 plus 6 equals 9"
what's going on here? haven't used mapply()
in while, maybe no-brainer... i'm using r version 3.4.0.
print
both prints argument , returns value.
p <- print("abc") # [1] "abc" p # [2] "abc"
so each element gets printed, vector of stuff gets returned (and printed). try e.g. invisible(mapply(...))
or m <- mapply(...)
comparison.
fwiw cat()
returns null
...
Comments
Post a Comment