Home > Blockchain >  Transforming Rows into a Single Indexed Column in R
Transforming Rows into a Single Indexed Column in R

Time:11-23

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

CodePudding user response:

What you need is convert your "wide" format data to "long" format. pivot_longer from tidyr package will help you.

library(tidyr)
library(tibble)

X %>% 
  rownames_to_column(var="id") %>% 
  pivot_longer(X1:X4, names_to = "x", values_to = "Y1") %>% 
  select(-x)
  •  Tags:  
  • r
  • Related