Goal
The goal of this tutorial is to know how to replace an specific value in different positions of a dataframe for another value using a for loop.
Data creation
To deploy the function a dataframe should be created.
## Dataframe generation from vectors
S001 <- c(100,-20, -30, -76, 100, 100, 0, -5, 100, -102, 100, 100, 100, -89, 100)
S002 <- c(100,100, -90, -44, 100, -10, 100, 100, 100, 100, -80, -6, 100, -67, 100)
S003 <- c( 0, -9, 100, -65, 100,100,-103, -30, -76, 100, 100, 100, 100, -77, 100)
S004 <- c( 100, -99, 100, 100, 100,-100,-103, 100, -76, -15, 100, 100, -79, 100, 100)
My_DataSet <- data.frame(S001,S002,S003,S004)
My_DataSet## S001 S002 S003 S004
## 1 100 100 0 100
## 2 -20 100 -9 -99
## 3 -30 -90 100 100
## 4 -76 -44 -65 100
## 5 100 100 100 100
## 6 100 -10 100 -100
## 7 0 100 -103 -103
## 8 -5 100 -30 100
## 9 100 100 -76 -76
## 10 -102 100 100 -15
## 11 100 -80 100 100
## 12 100 -6 100 100
## 13 100 100 100 -79
## 14 -89 -67 -77 100
## 15 100 100 100 100
Find specific value and replace
The aim of this section is evaluate all the positions of a dataframe compare with the value that we want to replace and replace it with the new one.
## Variables creation of the value to be replaced and new one
Old_value <- 100
# This could also be a multiple values subtitution like Old_value <- c(100, 150)
New_value <- 200## Loops to evaluate step by step the all of the positions of dataframe
## and assign the new valuein case the condition is fulfilled
for (i in seq_along(My_DataSet)) {
My_DataSet[[i]][My_DataSet[[i]] %in% Old_value] <- New_value
}
My_DataSet## S001 S002 S003 S004
## 1 200 200 0 200
## 2 -20 200 -9 -99
## 3 -30 -90 200 200
## 4 -76 -44 -65 200
## 5 200 200 200 200
## 6 200 -10 200 -100
## 7 0 200 -103 -103
## 8 -5 200 -30 200
## 9 200 200 -76 -76
## 10 -102 200 200 -15
## 11 200 -80 200 200
## 12 200 -6 200 200
## 13 200 200 200 -79
## 14 -89 -67 -77 200
## 15 200 200 200 200
Conclusions
In this tutorial we learned how to replace an specific value for another one.