Pasting items in a vector and grouping them into multiples of x, separated by whitespace

46 Views Asked by At

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)
2

There are 2 best solutions below

0
thelatemail On BEST ANSWER

Split and apply a function, using tapply and some integer division (%/%) to do the grouping:

tapply(a, (seq_along(a) - 1) %/% 4, FUN=paste, collapse="\n")
##               0                1                2                3                4 
##    "1\n2\n3\n4"     "5\n6\n7\n8"  "9\n10\n11\n12" "13\n14\n15\n16" "17\n18\n19\n20" 

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:

a <- 1:10
tapply(a, (seq_along(a) - 1) %/% 4, FUN=paste, collapse="\n")
##           0            1            2 
##"1\n2\n3\n4" "5\n6\n7\n8"      "9\n10" 
0
ThomasIsCoding On

If you have equal size for all groups, maybe you can use matrix + apply

> apply(matrix(a, 4), 2, paste0, collapse = "\n")
[1] "1\n2\n3\n4"     "5\n6\n7\n8"     "9\n10\n11\n12"  "13\n14\n15\n16"
[5] "17\n18\n19\n20"