0

I have a vector of data where every 4th row starts a new observation. I need to pivot the data so that first four values become the first row, the next four values become the second, and so on.

Here is a simplified example...

Given the following data:

a <- rep(c("a", "b", "c", "d"), 3)

The desired output is:

  A_lab B_lab C_lab D_lab
1     a     b     c     d
2     a     b     c     d
3     a     b     c     d
Stan
  • 905
  • 9
  • 20
  • 3
    Perhaps something like this: `as.data.frame(matrix(a, ncol = 4, byrow = TRUE))` if you want 4 columns? – Ben May 29 '21 at 02:01

3 Answers3

1

If you want a matrix, just call:

matrix(a, ncol=4, byrow=TRUE)

     [,1] [,2] [,3] [,4]
[1,] "a"  "b"  "c"  "d" 
[2,] "a"  "b"  "c"  "d" 
[3,] "a"  "b"  "c"  "d"

For a data.frame, pipe that result into data.frame:

data.frame(matrix(a, ncol=4, byrow=TRUE))

  X1 X2 X3 X4
1  a  b  c  d
2  a  b  c  d
3  a  b  c  d
GuedesBF
  • 8,409
  • 5
  • 19
  • 37
0

Here's an option using dplyr and the tidyverse

require(tidyverse)
a <- rep(c("a", "b", "c", "d"), 3)

labs = rep(c("A_lab", "B_lab", "C_lab", "D_lab"), 3)
obs_id <- rep(1:3, each=length(unique(a)))


tibble(vals = a, labs = labs,  obs_id = obs_id) %>%
  pivot_wider(obs_id, values_from = vals, names_from = labs)


# A tibble: 3 x 5
#  obs_id A_lab B_lab C_lab D_lab
#   <int> <chr> <chr> <chr> <chr>
#1      1 a     b     c     d    
#2      2 a     b     c     d    
#3      3 a     b     c     d 
ltr
  • 332
  • 2
  • 9
0
a <- rep(c("a", "b", "c", "d"), 3)

library(tidyverse)
a %>% as.data.frame() %>% setNames('V') %>%
  mutate(dummy = (( row_number() -1) %% 4)+1) %>%
  pivot_wider(names_from = dummy, values_from = V, values_fn = list) %>%
  unnest(everything())
#> # A tibble: 3 x 4
#>   `1`   `2`   `3`   `4`  
#>   <chr> <chr> <chr> <chr>
#> 1 a     b     c     d    
#> 2 a     b     c     d    
#> 3 a     b     c     d

Created on 2021-06-01 by the reprex package (v2.0.0)

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45