A.Naskar A.Naskar - 9 months ago 65
R Question

apply rbind for all column of a data frame in r

I have a data frame like this :

a <- 1:5
b <- c("a","b","c","d","e")
c <- c(15,49,41,29,7)

df1 <- data.frame(a,b,c)

I want to make a single column by doing r bind.
Currently I am doing like this :

x <- as.data.frame(df1$a)
y <- as.data.frame(df1$b)
z <- as.data.frame(df1$c)

colnames(x)[1] <- "x"
colnames(y)[1] <- "x"
colnames(z)[1] <- "x"

e <- rbind(x,y,z)

But problem is if number of column is huge like 50-60 it is very difficult to do the same.
Need help...


You can use unlist to coerce it to a vector, i.e. unlist(df1) but you have to make sure that you don't have any factor columns and also keep in mind that by doing that you are coercing your numeric columns to characters.

For your example above, this will not work as df1$b is a factor. You will have to convert it to character first.