0

I want to replace those values of df1$colB with values from df2$replacement where df1$colB is equal to df2$matches.

df1 <- data.frame(colA = 1:10, colB = letters[1:10])

df2 <- data.frame(matches= letters[4:1], replacement= LETTERS [4:1])

The result should look like df3:

df3 <- data.frame(colA =1:10, colB = c(LETTERS[1:4],letters[5:10]))

I'd like to avoid a for-loop solution for this task.

2 Answers 2

3

You could use the chartr function in base R.

# read in data with character vectors, not factors
df1 <- data.frame(colA = 1:10, colB = letters[1:10], stringsAsFactors=F)
df2 <- data.frame(matches= letters[4:1], replacement= LETTERS [4:1], stringsAsFactors=F)
df3 <- data.frame(colA =1:10, colB = c(LETTERS[1:4],letters[5:10]), stringsAsFactors=F)

# replace the characters with the desired characters
df1$colB <- chartr(paste(df2$matches, collapse=""), 
                   paste(df2$replacement, collapse=""), df1$colB)

According to the help file, `?chartr, the function

Translate(s) characters in character vectors

Sign up to request clarification or add additional context in comments.

Comments

3

You can do a merge on df1 and df2, and then replace the colB value by the replacement:

library(dplyr)
merge(df1, df2, by.x = "colB", by.y = "matches", all.x = T) %>% 
  mutate(colB = ifelse(!is.na(replacement), replacement, colB)) %>%  
  select(colA, colB)
   colA colB
1     1    A
2     2    B
3     3    C
4     4    D
5     5    e
6     6    f
7     7    g
8     8    h
9     9    i
10   10    j

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.