Shahzad
Shahzad

Reputation: 2049

Adding columns to data.frame in R

Having 2 vectors like the following:

vec1<-c("x", "y")
vec2<-c(rep(0, 5))

I would like to create a data.frame object where vec1 becomes the 1st of column of data.frame DF and vec2 becomes the row with column names too. Visually talking, it may be like this.

 vec1  1   2   3   4   5
 x     0   0   0   0   0
 y     0   0   0   0   0

I have tried the following code, but it adds both vectors as columns:

 DF<-data.frame(vec1, vec2)

Upvotes: 1

Views: 8142

Answers (2)

Didzis Elferts
Didzis Elferts

Reputation: 98419

You can use rbind() inside the data.frame() function to put vec2 values in both rows of new data frame.

vec1<-c("x", "y")
vec2<-c(rep(0, 5))
data.frame(vec1,rbind(vec2,vec2))

  vec1 X1 X2 X3 X4 X5
1    x  0  0  0  0  0
2    y  0  0  0  0  0

Upvotes: 1

juba
juba

Reputation: 49033

Instead of generating a vector for your rows, you can generate a whole matrix, and then use data.frame to bind it to your first vector. Something like this :

mat <- matrix(0, nrow=2, ncol=5)
vec <- c("x","y")
data.frame(vec, mat)

Which gives :

  vec X1 X2 X3 X4 X5
1   x  0  0  0  0  0
2   y  0  0  0  0  0

Upvotes: 2

Related Questions