R Conditional Replacement of Certain Values in Data Frame (Example Code)
In this R article you’ll learn how to exchange specific values in the columns of a data frame based on a logical condition.
Creation of Example Data
my_df <- data.frame(x1 = 1:10, # Creating example data frame x2 = 5:14, x3 = 7) my_df # Showing example data frame in RStudio console # x1 x2 x3 # 1 1 5 7 # 2 2 6 7 # 3 3 7 7 # 4 4 8 7 # 5 5 9 7 # 6 6 10 7 # 7 7 11 7 # 8 8 12 7 # 9 9 13 7 # 10 10 14 7 |
my_df <- data.frame(x1 = 1:10, # Creating example data frame x2 = 5:14, x3 = 7) my_df # Showing example data frame in RStudio console # x1 x2 x3 # 1 1 5 7 # 2 2 6 7 # 3 3 7 7 # 4 4 8 7 # 5 5 9 7 # 6 6 10 7 # 7 7 11 7 # 8 8 12 7 # 9 9 13 7 # 10 10 14 7
Example: Replace Certain Value in Data Frame by New Value
my_df[my_df == 7] <- 555 # Replace 7 by 555 my_df # Print new data frame # x1 x2 x3 # 1 1 5 555 # 2 2 6 555 # 3 3 555 555 # 4 4 8 555 # 5 5 9 555 # 6 6 10 555 # 7 555 11 555 # 8 8 12 555 # 9 9 13 555 # 10 10 14 555 |
my_df[my_df == 7] <- 555 # Replace 7 by 555 my_df # Print new data frame # x1 x2 x3 # 1 1 5 555 # 2 2 6 555 # 3 3 555 555 # 4 4 8 555 # 5 5 9 555 # 6 6 10 555 # 7 555 11 555 # 8 8 12 555 # 9 9 13 555 # 10 10 14 555