Skip to content

Instantly share code, notes, and snippets.

@amdevine
Created December 12, 2019 20:26
Show Gist options
  • Select an option

  • Save amdevine/e6232f5f6be41d57540b36300ca293ab to your computer and use it in GitHub Desktop.

Select an option

Save amdevine/e6232f5f6be41d57540b36300ca293ab to your computer and use it in GitHub Desktop.
Change values in a column of an R data frame
library(tidyverse)
#### Changing the values in a character/numeric vector ####
# Create sample data frame
df <- data.frame(
col1 = c("A", "A", "A", "A", "B", "B", "B", "B"),
col2 = c("C", "C", "D", "D", "C", "C", "D", "D"),
col3 = c("E", "F", "E", "F", "E", "F", "E", "F"),
stringsAsFactors = FALSE
)
# Change values in col1 from "A" to "Apple"
# From https://stackoverflow.com/questions/35610437/using-dplyr-to-conditionally-replace-values-in-a-column
df <- df %>%
mutate(col1 = replace(col1, col1 == "A", "Apple"))
#### Changing the value of a factor ####
# Create sample data frame
df <- data.frame(
col1 = c("A", "A", "A", "A", "B", "B", "B", "B"),
col2 = c("C", "C", "D", "D", "C", "C", "D", "D"),
col3 = c("E", "F", "E", "F", "E", "F", "E", "F"),
stringsAsFactors = TRUE
)
# Change values in col1 from "A" to "Apple". Change is made directly to df, don't need to reassign.
# From http://www.cookbook-r.com/Manipulating_data/Renaming_levels_of_a_factor/
levels(df)[levels(df) == "A"] <- "Apple"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment