Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename a column with R

Tags:

r

I'm trying to rename a specific column in my R script using the colnames function but with no sucess so far.

I'm kinda new around programming so it may be something simple to solve.

Basically, I'm trying to rename a column called Reviewer Overall Notes and name it Nota Final in a data frame called notas with the codes:

colnames(notas$`Reviewer Overall Notes`) <- `Nota Final`

and it returns to me:

> colnames(notas$`Reviewer Overall Notes`) <- `Nota Final`
Error: object 'Nota Final' not found

I also found in [this post][1] a code that goes:

colnames(notas) [13] <- `Nota Final`

But it also return the same message.

What I'm doing wrong?

Ps:. Sorry for any misspeling, English is not my primary language.

like image 268
Lucas Correa Avatar asked Oct 28 '25 05:10

Lucas Correa


2 Answers

You probably want

colnames(notas)[colnames(notas) == "Reviewer Overall Notes"] <- "Nota Final"

(@Whatif's answer shows how you can do this with the numeric index, but probably better practice to do it this way; working with strings rather than column indices makes your code both easier to read [you can see what you're renaming] and more robust [in case the order of columns changes in the future])

Alternatively,

notas <- notas %>% dplyr::rename(`Nota Final` = `Reviewer Overall Notes`)

Here you do use back-ticks, because tidyverse (of which dplyr is a part) prefers its arguments to be passed as symbols rather than strings.

like image 139
Ben Bolker Avatar answered Oct 31 '25 13:10

Ben Bolker


Why using backtick? Use the normal quotation mark.

colnames(notas)[13] <- 'Nota Final'

This seems to matter:

df <- data.frame(a = 1:4)
colnames(df)[1] <- `b`

Error: object 'b' not found

like image 29
WhatIf Avatar answered Oct 31 '25 12:10

WhatIf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!