Renaming an observation category in a dataset

I'm looking for code to change observation variables in a dataset , many options so far don't seem to make sense or work.
Any help will be appreciated. Thanks so much.

the code below changed the row character name , I wanted the name to be connected with the_underscore connector symbol

mydata = mydata[mydata == "change item"] <- "change_item"

Hi,

Welcome to the RStudio community!

There ar multiple ways of doing this. Here are some examples:

#Dummy data
myData = data.frame(
  id = 1:5,
  value = c("A", "A", "B", "C", 'D')
)
myData
#>   id value
#> 1  1     A
#> 2  2     A
#> 3  3     B
#> 4  4     C
#> 5  5     D

#Option 1
myData$value[myData$value == "A"] = "X"

#Option 2
myData[myData$value == "A", "value"] = "X"

myData
#>   id value
#> 1  1     X
#> 2  2     X
#> 3  3     B
#> 4  4     C
#> 5  5     D

Created on 2022-06-06 by the reprex package (v2.0.1)

If you like to change multiple values at once you can also use the case_when() function from the dplyr package (or alternatively write longer if-else statements)

#In case of multiple changes at once
library(dplyr)

myData = data.frame(
  id = 1:5,
  value = c("A", "A", "B", "C", 'D')
)

myData$value = case_when(
  myData$value == "A" ~ "X",
  myData$value %in% c("B", "C") ~ "Y",
  TRUE ~ "Z"
)
myData
#>   id value
#> 1  1     X
#> 2  2     X
#> 3  3     Y
#> 4  4     Y
#> 5  5     Z

Created on 2022-06-06 by the reprex package (v2.0.1)

Hope this helps,
PJ

Thank you PieterJanvc , your solutions are very helpful indeed.

I really appreciate your help and all the best to you.

Rod

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.