In R programming language, we can change (replace) certain values in a dataset only when a condition is true. This is called replacing values based on a condition.
Method 1: Replacing value based on a Single condition
We replace values in a column when a single condition is true.
Example 1: We will replace values in the age column where age == 24.
- df: The data frame with columns name, age and id_no.
- df$age == 24: Condition - selects rows where age is 24.
- df$age[...] <- 55: Replaces those values with 55.
df <- data.frame(
name = c("A", "B", "C", "D", "E"),
age = c(24, 21, 23, 25, 24),
id_no = c(4203, 4438, 4477, 4486, 4576)
)
print("The data frame is")
print(df)
df$age[df$age == 24] <- 55
print("Replacing value based on single condition")
print(df)
Output:

Example 2: We will replace values in the C column where C == "abc".
- df: The data frame with columns
A,BandC. - df$C == "abc": Condition - selects rows where C is "abc".
- df$C[...] <- "gfg": Replaces those values with "gfg".
df <- data.frame(
A = 10:14,
B = c("a", "b", "c", "d", "a"),
C = c("abc", "def", "mno", "pqr", "abc")
)
print("The data frame is")
print(df)
df$C[df$C == "abc"] <- "gfg"
print("Replacing value based on single condition")
print(df)
Output:

Method 2: Replacing value based on Multiple Conditions
We replace values in a column only when two or more conditions are true.
Example 1: We will replace values in the nos column where nos == 50 and r_no == 105.
- df: The data frame with columns nos, r_no and emp_id.
- df$nos == 50: First condition – selects rows where nos is 50.
- df$r_no == 105: Second condition – selects rows where r_no is 105.
- &: Combines both conditions (AND condition).
- df$nos[...] <- 600: Replaces matching nos values with 600.
nos <- c(50, 20, 30, 40, 50)
r_no <- c(105, 102, 103, 104, 105)
emp_id <- c(2302:2306)
df <- data.frame(nos, r_no, emp_id)
print("The data frame is")
print(df)
df$nos[df$nos == 50 & df$r_no == 105] <- 600
print("Replacing value based on multiple conditions")
print(df)
Output:

Example 2: We will replace values in the state column where state == "odhisa" and name == "kumari".
- df: The data frame with columns
name,sexandstate. - df$state == "odhisa": First condition - selects rows where state is "odhisa".
- df$name == "kumari": Second condition - selects rows where name is "kumari".
- &: Combines both conditions.
- df$state[...] <- "Hyderabad": Replaces matched values in state with "Hyderabad".
df <- data.frame(
name = c("ramya", "kumari", "raghu", "sravya", "kumari"),
sex = c("F", "F", "M", "F", "F"),
state = c("Andhra pradesh", "odhisa", "delhi", "kerla", "odhisa")
)
print("The data frame is")
print(df)
df$state[df$state == "odhisa" & df$name == "kumari"] <- "Hyderabad"
print("Replacing value based on multiple conditions")
print(df)
Output:

The output shows that the value "odhisa" is replaced with "Hyderabad" only for rows where the name is "kumari". All other rows remain unchanged.