recode some rows of dataframe in r

To recode some rows of a dataframe in R, one can use the mutate() function from the dplyr package in combination with the ifelse() statement. Here is an example code that recodes values in a dataframe column:

main.r
library(dplyr)

# create example dataframe
df <- data.frame(
  var1 = c(1, 2, 3, 4, 5),
  var2 = c("A", "B", "C", "D", "E")
)

# recode values in var1 column
df <- mutate(df, var1 = ifelse(var1 == 3 | var1 == 4, 99, var1))
223 chars
11 lines

In this example, rows with values 3 and 4 in the var1 column are recoded to 99, while all other rows retain their original values. The ifelse() statement checks whether each row meets a certain condition (in this case, if the value in var1 is equal to 3 or 4), and if so, replaces it with a new value (in this case, 99). The mutate() function applies this recoding to the var1 column and saves the result back to the original dataframe.

gistlibby LogSnag