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.

1
  • Hi, you can try df <- data.frame(col1,col2,col3) instead. Commented Jun 13, 2020 at 21:00

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

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!
If you feel I have answered your question, don't erase it and please feel free to grant me an answer credit
The reason behind the loss of column names has perhaps already been answered here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.