Aaron Schlegel
Aaron Schlegel

Reputation: 19

How do you make a single column multiple columns in R?

Say you have a single column that is 100 rows in length. I want to reshape the data such that the first 10 rows become a single row of 10 columns, then the next 10 rows fill row 2, and so on.

Upvotes: 0

Views: 491

Answers (2)

user10917479
user10917479

Reputation:

If it is a single column of numeric data, you can easily convert to a matrix and then back to a data frame using byrow = TRUE. You still will need to name the columns accordingly.

df <- data.frame(x = 1:100)

as.data.frame(matrix(df$x, ncol = 10, byrow = TRUE))

Upvotes: 2

akrun
akrun

Reputation: 887138

Here, is one option by creating a grouping column based on the n of 10 with gl, then with a sequene column created with rowid, we pivot to 'wide' format

library(dplyr)
library(tidyr)
library(data.table)
df1 %>%
    mutate(colnew = as.integer(gl(n(), 10, n())),
            rn = str_c('col', rowid(colnew))) %>%
     pivot_wider(names_from = rn, values_from = col1) %>%
     select(-colnew)
# A tibble: 6 x 10
#     col1    col2   col3   col4   col5    col6    col7    col8   col9    col10
#    <dbl>   <dbl>  <dbl>  <dbl>  <dbl>   <dbl>   <dbl>   <dbl>  <dbl>    <dbl>
#1 -0.546   0.537   0.420 -0.584  0.847  0.266   0.445  -0.466  -0.848  0.00231
#2 -1.32    0.598  -0.762 -1.43   0.332 -0.469  -0.335   1.54    0.610  0.516  
#3 -0.0743 -0.605  -1.71  -0.269 -0.649 -0.0941 -0.0855  0.120  -0.116 -0.944  
#4 -0.0337 -0.585   0.613  1.52   0.657 -1.07   -4.47    0.369   0.169 -1.82   
#5  0.0674  0.0171 -0.344 -0.668 -0.256 -0.461   1.47   -0.0920  0.335 -0.232  
#6  0.527  -1.07    0.770  1.77  -0.196  0.205  -0.597  NA      NA     NA      

data

set.seed(24)
df1 <- data.frame(col1 = rnorm(57))

Upvotes: 0

Related Questions