1

I am working with the R programming language. Suppose I have the following dataset:

a = rnorm(10,10,10)

b = rnorm(10, 6, 7)

c = rnorm( 10, 5, 5)

d = data.frame(a,b,c)

 head(d)
           a          b          c
1 18.3615091 -1.1253320  0.3403199
2  4.9365020  2.4014072 -3.5771919
3 12.5686200  0.7474177 -4.6788551
4  0.1913607 -0.6456205  3.8693564
5  9.1718179 16.1776224  8.1820692
6 18.3757202  4.1313655 -0.4195688

Is it possible to convert this data set into a single column of data (i.e. 1 column and 30 rows)?

I tried a few ways:

#first way
d = data.frame(a + b + c)

#second way

d = cbind(a,b,c)

#third way 

d = rbind(a,b,c)

But nothing seems to work.

Can someone please show me how to do this?

Thanks

Sotos
  • 51,121
  • 6
  • 32
  • 66
stats_noob
  • 5,401
  • 4
  • 27
  • 83

2 Answers2

2

You may first convert the dataframe to a matrix. Matrices in R are stored in column-major order, so(*) if you convert the matrix to a vector, you will get the stacked columns as a vector:

as.vector(as.matrix(d))

If you want dataframe instead:

data.frame(stack = as.vector(as.matrix(d)))

(*) In R a matrix is just a vector with a dimension attribute, and the data is stored in column-major order in the vector. For instance:

structure(1:4, dim = c(2, 2))

     [,1] [,2]
[1,]    1    3
[2,]    2    4

When you convert a matrix to a vector, you simply remove the dimension.

as.vector(.Last.value)

[1] 1 2 3 4
1

You may try stack or reshape2::melt or tidyr::pivot_longer

stack(d)
reshape2::melt(d)
tidyr::pivot_longer(c(a,b,c))

will work.

Park
  • 14,771
  • 6
  • 10
  • 29