Eric Morales Mora
Eric Morales Mora

Reputation: 5

How to stack columns of data-frame in r?

I have a data-frame with these characteristics:

Z Y X1 X2 X3 X4 X5 ... X30 

A n1 1 2 1 2 1 2 1      2

B n2 1 2 1 2 1 2 1      2

C n3 1 2 1 2 1 2 1      2

D n4 1 2 1 2 1 2 1      2

.
.
. 

My purpose is to stack the column x1, x2, … x30, and associated the new column with columns z, y, and x. Some like this:

Newcolumn zyx
1                    x-y-z

... I need a data-frame like this:


  colum1                  colum2  

1 A+n1+X1.headername      1

2 B+n2+X2.headernam       2

3 C+n3X3.headername       1

4 D+n4X4.headername       2

.                         .
.                         .
.                         . 

I’m trying to build a function, but I have some troubles I follow this code for the data-frame:

df$zy <- paste(df$z,"-",df$y)

After that, I eliminate the columns “z” and “y”:

df$z <- NULL
df$y <- NULL

And save column df$zy as data-frame for use later:

df_zy <- as.data.frame(df$zy)

Then eliminate df$xy of original dataframe:

df$xy <- NULL

After that, I save as data-frame the column x1, and incorporate df_zy and name of column x1 (the name is “1”):

a <- as.data.frame(df$`1`)
b <- cbind(a, df_xy, x_column= 1)
b$zy <- paste(b$x_column,"-",b$` df$zy`)
b$` df$zy ` <- NULL
b$ x_column <- NULL
colnames(b)
names(b)[names(b) == "b$`1`"] <- "new_column"

This works, but only for the column x1 and I need this for x1 to x30, and stack all new column

Does anybody have an answer to this problem? Thanks!

Upvotes: 0

Views: 54

Answers (1)

dc37
dc37

Reputation: 16178

You can use tidyr and dplyr librairies:

library(dplyr)
library(tidyr)
df_zy = df %>% pivot_longer(., cols = starts_with("X"), names_to = "Variables", values_to = "Value") %>%
  mutate(NewColumn = paste0(Z,"-",Y,"-",Variables)) %>% select(NewColumn, Value)

And you get:

> df_zy
# A tibble: 8 x 2
  NewColumn Value
  <chr>     <dbl>
1 A-n1-X1       1
2 A-n1-X2       2
3 B-n2-X1       1
4 B-n2-X2       2
5 C-n3-X1       1
6 C-n3-X2       2
7 D-n4-X1       1
8 D-n4-X2       2

Data

df = data.frame("Z" = LETTERS[1:4],
                "Y" = c("n1","n2","n3","n4"),
                "X1" = c(1,1,1,1),
                "X2" = c(2,2,2,2))

Is it what you are looking for ?

Upvotes: 1

Related Questions