Replace Values In Data Frame Conditionally In R (4 Examples)
Maybe your like
In this tutorial, I’ll show how to exchange specific values in the columns of a data frame based on a logical condition in R.
The content of the article looks like this:
1) Creation of Example Data 2) Example 1: Conditionally Exchange Values in Numeric Variable 3) Example 2: Conditionally Exchange Values in Character Variable 4) Example 3: Conditionally Exchange Values in Factor Variable 5) Example 4: Conditionally Exchange All Values in Whole Data Frame 6) Video & Further Resources 7) Subscribe to the Statistics Globe Newsletter 8) Thank you!So without further ado, here’s how to do it!
Creation of Example Data
As a first step, we’ll have to create some data that we can use in the examples below:
data <- data.frame(num1 = 1:5, # Example data num2 = 3:7, char = letters[1:5], fac = as.factor(c("gr1", "gr2", "gr1", "gr3", "gr2"))) data # Print example data # num1 num2 char fac # 1 1 3 a gr1 # 2 2 4 b gr2 # 3 3 5 c gr1 # 4 4 6 d gr3 # 5 5 7 e gr2Have a look at the previous RStudio console output. It shows that the example data contains of four columns. Two of the variables are numeric, one of the variables is a character, and another one of the variables has the factor class.
Let’s exchange some of the values in our data conditionally!
Example 1: Conditionally Exchange Values in Numeric Variable
The following R programming syntax illustrates how to perform a conditional replacement of numeric values in a data frame variable. Have a look at the following R code:
data$num1[data$num1 == 1] <- 99 # Replace 1 by 99 data # Print updated data # num1 num2 char fac # 1 99 3 a gr1 # 2 2 4 b gr2 # 3 3 5 c gr1 # 4 4 6 d gr3 # 5 5 7 e gr2As you can see based on the previous output, we have replaced the value 1 by the value 99 in the first column of our data frame.
Example 2: Conditionally Exchange Values in Character Variable
This Example illustrates how to insert new values in character variables. The syntax is basically the same as in Example 1. However, this time the values should be wrapped with quotation marks:
data$char[data$char == "b"] <- "XXX" # Replace b by XXX data # Print updated data # num1 num2 char fac # 1 99 3 a gr1 # 2 2 4 XXX gr2 # 3 3 5 c gr1 # 4 4 6 d gr3 # 5 5 7 e gr2The previous R code replaced the character “b” with the character string “XXX”.
Example 3: Conditionally Exchange Values in Factor Variable
Example 3 shows how to replace factor levels. The exchange of values in factors is slightly more complicated as in case of numeric or character vectors. If you would use the code shown in Examples 1 and 2, the following Warning would be shown:
# Warning: # In `[<-.factor`(`*tmp*`, data$fac == "gr1", value = c(NA, 2L, NA, : # invalid factor level, NA generatedThe reason is that factor variables have fixed factor levels. When we insert new values to our factor, the factor variable cannot assign the values to an existing factor level and for that reason NA values (i.e. missing values) are generated.
For that reason, we have to convert our factor column to the character data type first:
data$fac <- as.character(data$fac) # Convert factor to characterNow, we can apply the same code as in Example 2:
data$fac[data$fac == "gr1"] <- "new_group" # Replace gr1 by new_groupAnd finally, we can convert the character variable back to the factor class:
data$fac <- as.factor(data$fac) # Convert character to factorLet’s have a look at the new data:
data # Print updated data # num1 num2 char fac # 1 99 3 a new_group # 2 2 4 XXX gr2 # 3 3 5 c new_group # 4 4 6 d gr3 # 5 5 7 e gr2As you can see, the factor level gr2 was replaced by the new factor level new_group.
Example 4: Conditionally Exchange All Values in Whole Data Frame
It is also possible to replace a certain value in all variables of a data frame. The following R code shows how to do that:
data[data == 3] <- 777 # Replace all values data # Print updated data # num1 num2 char fac # 1 99 777 a new_group # 2 2 4 XXX gr2 # 3 777 5 c new_group # 4 4 6 d gr3 # 5 5 7 e gr2We just replaced the value 3 by 777 in all columns of our data matrix.
Video & Further Resources
I have recently published a video on my YouTube channel, which explains the R syntax of this tutorial. Please find the video below.
In addition, you might have a look at the related articles of my homepage.
- Convert Character to Factor in R
- Replace Particular Value in Data Frame
- Replace Multiple Letters with Accents
- Replace Inf with NA in Vector & Data Frame
- Replace 0 with NA in R
- replace Function in R
- The R Programming Language
In this R tutorial you learned how to replace certain data frame values. Please let me know in the comments section, if you have any additional questions. Furthermore, don’t forget to subscribe to my email newsletter in order to get updates on the newest tutorials.
Get regular updates on the latest tutorials, offers & news at Statistics Globe.I hate spam & you may opt out anytime: Privacy Policy.
SubscribeLoading...
Thank you!
Please check your email inbox and click the confirmation link to complete your subscription. If you don’t see the email within a few minutes, please also check your spam/junk folder.
Tag » Add Column From One Dataframe To Another Based On Condition R
-
Add A New Column To A Dataframe Using Matching Values Of Another ...
-
R: Add A Column To Dataframe Based On Other Columns With Dplyr
-
How To Add A Column To A Dataframe In R With Tibble & Dplyr
-
Add New Column In Dataframe Based On Condition From Another ...
-
4 Data Wrangling Tasks In R For Advanced Beginners - Computerworld
-
Add A Column In A Pandas DataFrame Based On An If-Else Condition
-
How To Insert A New Column Based On Condition In Python?
-
How To Add A Column Based On Other Columns In R DataFrame
-
How To Add Column From Another DataFrame In Pandas
-
R: How To Add Column To Data Frame Based On Other Columns
-
How To Add A Column To A DataFrame In Python Pandas
-
Select Rows In DataFrame By Conditions On Multiple Columns
-
Joining Pandas Dataframes - Data Carpentry
-
How To Assign A Column Value In A Data Frame Based On Another ...