Kevin
Kevin

Reputation: 2054

R: Replace values of dataframe from another using row/column

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

Upvotes: 1

Views: 294

Answers (1)

akrun
akrun

Reputation: 887951

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

Upvotes: 2

Related Questions