If I have the following vector containing some data e.g.
a <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
Suppose I want to take these 20 values and group them into 4s in the order they are arranged, like so
[1] "1\n2\n3\n4" "5\n6\n7\n8" "9\n10\n11\n12" "13\n14\n15\n16" "17\n18\n19\n20"
How would I do that? I started off with the paste function but I'm stuck :( I'm assuming it would involve a for loop.
paste(a)
Split and apply a function, using
tapplyand some integer division (%/%) to do the grouping:This will work for any size split, and will also deal with overflow at the end in instances where the group size doesn't neatly divide: