when patterns match in cells between two columns replace the second column with the value in the first in r

You can use the ifelse function to replace values in the second column based on pattern matching with the first column. Here is an example code snippet to achieve this:

# Sample data
df <- data.frame(col1 = c("apple", "banana", "cherry", "banana"), 
                 col2 = c("orange", "banana", "grape", "kiwi"))

# Replace values in col2 based on pattern matching with col1
df$col2 <- ifelse(df$col1 == df$col2, df$col1, df$col2)

# Print the updated dataframe
print(df)
304 chars
10 lines

In this code, we first create a sample dataframe df with two columns col1 and col2. We then use ifelse to check if the value in col1 matches the value in col2, and if it does, we replace the value in col2 with the value in col1.

gistlibby LogSnag