2

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.

Beto
  • 21
  • 4

1 Answers1

1

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
Daniel_j_iii
  • 3,041
  • 2
  • 11
  • 27
  • I've just tried. I came here to erase the question and I read your comment. My mind was very tired, and I didn't see this idiot mistake. By the way, THANK YOU! – Beto Jun 13 '20 at 21:53
  • If you feel I have answered your question, don't erase it and please feel free to grant me an answer credit – Daniel_j_iii Jun 13 '20 at 21:55
  • The reason behind the loss of column names has perhaps already been answered [here](https://stackoverflow.com/questions/5231540/r-losing-column-names-when-adding-rows-to-an-empty-data-frame) – tnotstar Jun 14 '20 at 00:55