Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

How to stack columns of data-frame in r?

$
0
0

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!


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>