Append row in data.frame using list of variable with same name of columns - R Language

Viewed 282

dears!

Summarizing my problem in a small example...

I want to append a row in data.frame using a list of variables with the same name of the data.frame columns, like this:

#createing a blank data.frame
df <- data.frame(matrix(ncol=3, nrow=0))
#naming the header    
head <- c("col1", "col2", "col3")
# assigning header to data.frame    
colnames(df) <- head
# creating three variables with the same name of header
col1 <- 1
col2 <- 2
col3 <- 3
#appending the row
rbind(df, list(col1, col2, col3))

The code runs, but the df continues blank. I would like a result like this for df:

col1    col2   col3
   1       2      3

Help me with this rbind.

1 Answers

If you use the names() function, you can rename the columns in R

#createing a blank data.frame
df <- data.frame(matrix(ncol=3, nrow=0))
#naming the header    
head <- c("col1", "col2", "col3")
# assigning header to data.frame    
colnames(df) <- head
# creating three variables with the same name of header
col1 <- 1
col2 <- 2
col3 <- 3
#appending the row
df2 <- rbind(df, list(col1, col2, col3))

names(df2) <- c("col1", "col2", "col3")

df2

produces the output below

  col1 col2 col3
     1    2    3
Related