Reputation: 497
I try to iterate over multiple vectors like Pythons "for x, y, z in zip(lia, lib, lic): ..." and found mapply
which does what I want, but it returns too much.
Example:
lia = c(1,2,3)
lib = c(4,5,6)
lic = c(7,8,9)
mapply(function(x, y, z) print(sprintf('%f %f %f', x, y, z)), lia, lib, lic )
Results in:
[1] "1.000000 4.000000 7.000000"
[1] "2.000000 5.000000 8.000000"
[1] "3.000000 6.000000 9.000000"
[[1]]
[1] "1.000000 4.000000 7.000000"
[[2]]
[1] "2.000000 5.000000 8.000000"
[[3]]
[1] "3.000000 6.000000 9.000000"
The first three lines are what I expect. Why it is returning more? How would I do it correctly?
Upvotes: 1
Views: 180
Reputation: 72909
When you use print
, mapply
still has it's own output which you may make invisible
. However, maybe you don't need print
at all.
Try one of the two:
invisible(mapply(function(x, y, z) print(sprintf('%f %f %f', x, y, z)), lia, lib, lic))
# [1] "1.000000 4.000000 7.000000"
# [1] "2.000000 5.000000 8.000000"
# [1] "3.000000 6.000000 9.000000"
mapply(function(x, y, z) sprintf('%f %f %f', x, y, z), lia, lib, lic)
# [1] "1.000000 4.000000 7.000000" "2.000000 5.000000 8.000000" "3.000000 6.000000 9.000000"
Upvotes: 1