Transforming Rows into Indexed Columns

Hi All,

I would like to transform my data of n rows into a columns indexed by row id.

Therefore, below, I would really appreciate if someone could show me how to transform X into Y if possible?

X1 <- c(1,2,3,2,2)
X2 <- c(1,2,3,2,2)
X3 <- c(1,2,3,3,2)
X4 <- c(1,2,2,2,2)

X <- data.frame(X1,X2, X3, X4)

  X1 X2 X3 X4
1  1  1  1  1
2  2  2  2  2
3  3  3  3  2
4  2  2  3  2
5  2  2  2  2

 id Y1
1  1
1  1
1  1
1  1
2  2
2  2
2  2
2  2
3  3
3  3
3  3
3  2
4  2
4  2
4  3
4  2
5  2
5  2
5  2
5  2

Here is one solution. You can drop the ColName column if you want to.

library(tidyverse)
X1 <- c(1,2,3,2,2)
X2 <- c(1,2,3,2,2)
X3 <- c(1,2,3,3,2)
X4 <- c(1,2,2,2,2)

X <- data.frame(X1,X2, X3, X4)

Y <- X |> mutate(id = row_number()) |> 
  pivot_longer(cols = -id, names_to = "ColName", values_to = "Y1")
Y
#> # A tibble: 20 × 3
#>       id ColName    Y1
#>    <int> <chr>   <dbl>
#>  1     1 X1          1
#>  2     1 X2          1
#>  3     1 X3          1
#>  4     1 X4          1
#>  5     2 X1          2
#>  6     2 X2          2
#>  7     2 X3          2
#>  8     2 X4          2
#>  9     3 X1          3
#> 10     3 X2          3
#> 11     3 X3          3
#> 12     3 X4          2
#> 13     4 X1          2
#> 14     4 X2          2
#> 15     4 X3          3
#> 16     4 X4          2
#> 17     5 X1          2
#> 18     5 X2          2
#> 19     5 X3          2
#> 20     5 X4          2

Created on 2022-11-22 with reprex v2.0.2

Hi @FJCC.

Thanks a lot for your help again.

Is it possible to remove the column name, so that Y would just be preserved as two columns, 'id' and 'Y1'?

One way to drop a column is to use the select() function.

Y <- X |> mutate(id = row_number()) |> 
  pivot_longer(cols = -id, names_to = "ColName", values_to = "Y1") |> 
  select(-ColName)
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.