1

I have a dataframe that I want to replace some of its values using another dataframe which I have row, column, and value information.

dat <- data.frame(Age = c(19,22,32,24),Names = c("Bobby","Mary","Bill","Chuck"), Sport = c("Golf","Tennis","Football","Soccer"))

  Age Names    Sport
   19 Bobby     Golf
   22  Mary   Tennis
   32  Bill Football
   24 Chuck   Soccer

valuesreplace <- data.frame(row = c(1,3), column = c(3,1), value = c("Basketball","18"))

  row column      value
    1      3 Basketball
    3      1         18

The result should be the following:

  Age Names      Sport
   19 Bobby Basketball
   22  Mary     Tennis
   18  Bill   Football
   24 Chuck     Soccer

1 Answer 1

2

We need to first convert the factor to character (use stringsAsFactors = FALSE while constructing both data.frames) and then use pass a matrix of row/column index select the values of 'dat' and assign values from 'valuesreplace' column 'value'

dat[as.matrix(valuesreplace[1:2])] <- valuesreplace$value
dat
#  Age Names      Sport
#1  19 Bobby Basketball
#2  22  Mary     Tennis
#3  18  Bill   Football
#4  24 Chuck     Soccer
Sign up to request clarification or add additional context in comments.

1 Comment

Holy response time! Yes, that works perfectly and good tip on converting factor to character. (I'll accept in 10 minutes when it lets me)

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.