I would like to create a numeric vector with the results of a loop such as
> for (i in 1:5) print(i+1)
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
It seems strange that the same expression without ‘print’ returns nothing
> for (i in 1:5) i+1
>
Does anyone have an explanation/solution?
This is standard behaiviour — when you say you want to create a numeric vector,
printwill not do thatThe expression in a for loop is an argument to the primitive function
forFrom
?`for`in the value sectionprintprints the results to the console.merely calculates
i + 1for each iteration and returns nothingIf you want to assign something then assign it using
<-, or less advisablyassignYou can avoid an explicit loops by using
sapply. This (should) avoid any pitfalls of growing vectors