r change column value conditionally
To change column values conditionally in R, you can use the ifelse()
function. This function allows you to specify a condition and provide values for when the condition is TRUE or FALSE. Here is an example of how to use ifelse()
to change column values conditionally:
# Create a data frame
df <- data.frame(A = c(1, 2, 3, 4, 5),
B = c(6, 7, 8, 9, 10))
# Change values in column B based on a condition
df$B <- ifelse(df$A > 3, "High", "Low")
In this example, we first create a data frame df
with two columns, A and B. The column A contains the values 1, 2, 3, 4, and 5, while column B initially contains the values 6, 7, 8, 9, and 10.
We then use the ifelse()
function to change the values in column B based on a condition. The condition we specify is df$A > 3
, which checks if the values in column A are greater than 3. If the condition is TRUE, the corresponding value in column B is set to "High". If the condition is FALSE, the corresponding value in column B is set to "Low".
After executing the code, the values in column B will be changed based on the condition. The resulting data frame will look like this:
A B
1 1 Low
2 2 Low
3 3 Low
4 4 High
5 5 High
By using the ifelse()
function, you can easily change column values conditionally in R based on specific criteria or conditions.