convert columns to rows

HI ,
I have a dataframe looks like this

actual_df <- data.frame(time = seq(1,10,3),
                        a1 = c(1,2,3,4),
                        a2 = c(2,5,7,8),
                        a3 = c(1,3,5,6))

i want add the third and fourth columns as rows, and keep the first column repeated. Below is the output i need

needed_df <- data.frame(time = rep(seq(1,10,3),3),
                        ID = rep(c("a1","a2","a3"),each = 4),
                        DV = c(1,2,3,4,2,5,7,8,1,3,5,6))

Thanks for your help

You can pivot the data with pivot_longer() from the tidyr package. If the order of the rows is important, you can rearrange them with the arrange function from the dplyr package.

library(tidyr)
library(dplyr)
actual_df <- data.frame(time = seq(1,10,3),
                        a1 = c(1,2,3,4),
                        a2 = c(2,5,7,8),
                        a3 = c(1,3,5,6))
df_long <- pivot_longer(actual_df, cols = a1:a3, 
                        names_to = "ID",values_to = "DV")
df_long  
#> # A tibble: 12 × 3
#>     time ID       DV
#>    <dbl> <chr> <dbl>
#>  1     1 a1        1
#>  2     1 a2        2
#>  3     1 a3        1
#>  4     4 a1        2
#>  5     4 a2        5
#>  6     4 a3        3
#>  7     7 a1        3
#>  8     7 a2        7
#>  9     7 a3        5
#> 10    10 a1        4
#> 11    10 a2        8
#> 12    10 a3        6
df_long <- arrange(df_long,ID, time)
df_long
#> # A tibble: 12 × 3
#>     time ID       DV
#>    <dbl> <chr> <dbl>
#>  1     1 a1        1
#>  2     4 a1        2
#>  3     7 a1        3
#>  4    10 a1        4
#>  5     1 a2        2
#>  6     4 a2        5
#>  7     7 a2        7
#>  8    10 a2        8
#>  9     1 a3        1
#> 10     4 a3        3
#> 11     7 a3        5
#> 12    10 a3        6

Created on 2023-07-31 with reprex v2.0.2

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.