Question

I have a data frame df

 > df<-data.frame(a=letters[1:5], b=1:5, c=LETTERS[1:5])
 > df
   a  b c
1  a  1 A
2  b  2 B
3  c  3 C
4  d  4 D
5  e  5 E

and I want to create a new data frame from the above data frame with only column which should look like this

> df1
   a
1  a
2  1
3  A
4  b
5  2
6  B
7  c
8  3
9  C
.....

I tried the following

> df1<-data.frame(c(df[1,],df[2,],df[3,]))
> df1
  a b c a.1 b.1 c.1 a.2 b.2 c.2
1 a 1 A   b   2   B   c   3   C

But the result is row matrix and in real I have hundreds of columns and rows which should be transformed to one column. How can I do it?

Was it helpful?

Solution

> data.frame(a = matrix(apply(df, 1, c), ncol = 1))
##    a
## 1  a
## 2  1
## 3  A
## 4  b
## 5  2
## 6  B
## 7  c
## 8  3
## 9  C
## 10 d
## 11 4
## 12 D
## 13 e
## 14 5
## 15 E

Here are another couple of options,

> data.frame(a = do.call(rbind, as.list(t(df))))
## or
> data.frame(a = c(apply(df, 1, c)))

as.vector and as.matrix will also work in place of c in the apply call above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top