0

I have raw data with multiple observation and I have a cleaning log which contains some new values for specific columns of raw data I want to replace old values with these new ones.

My raw data is :

raw_df<- data.frame(
                    id=c(1,2,3,4),
                    name=c("a","b","c","d"),
                    age=c(15,16,20,22),
                    add=c("xyz","bc","no","da")
                   )

MY cleaning log is :

cleaning_log <- data.frame(
                             id=c(2,4),
                             question=c("name","age"), 
                             old_value=c("b",22),
                             new_value=c("bob",25)
                          )

And my expected result is :

result<-data.frame(
                      id=c(1,2,3,4),
                      name=c("a","bob","c","d"),
                      age=c(15,16,20,25),
                      add=c("xyz","bc","no","da")
                  )

Note:At the end how can I check whether these new values are replaced properly or not? In addition, in cleaning log question column I may have more than two columns like 10 to 20 which possibly will have new value but here I just give two column names as an example. Thanks in advance for you help

1 Answer 1

3

Find out the row number and column number to change in raw_df using match and replace it with cleaning_log$new_value.

row_inds <- match(cleaning_log$id, raw_df$id)
col_inds <-  match(cleaning_log$question, names(raw_df))
raw_df[cbind(row_inds, col_inds)] <- cleaning_log$new_value
raw_df

#  id name age add
#1  1    a  15 xyz
#2  2  bob  16  bc
#3  3    c  20  no
#4  4    d  25  da
Sign up to request clarification or add additional context in comments.

2 Comments

and how to check whether they are replaced properly?
You can manually check 3-4 values if they are replaced correctly.

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.