Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove values in one data frame based upon cell reference in another data frame

Tags:

r

I'm sure this is simple but cannot find an answer for it. I have a data frame df:

df <- data.frame(replicate(10,sample(0:10,1000,rep=TRUE)))

I then have another smaller data frame that has cell references (row and column numbers) referring to specific cells in df that should be empty (i.e. NA):

cellRefs <- data.frame(replicate(2,sample(1:10,10,rep=TRUE)))

How do I go about replacing all the cells in df with NA that are referred to by the row and column references from cellRefs?

like image 900
Stinky_Goat Avatar asked Mar 11 '26 11:03

Stinky_Goat


2 Answers

We could convert the 'cellRefs' into a matrix and use as row/column index to assign those elements in 'df' to NA

df[as.matrix(cellRefs)] <- NA
like image 152
akrun Avatar answered Mar 13 '26 18:03

akrun


Maybe not the fastest way, but it works with a loop across cellRefs rows.

for (i in 1:nrow(cellRefs)){
  df[cellRefs[i,1],cellRefs[i,2]] = NA
}
like image 43
Arault Avatar answered Mar 13 '26 17:03

Arault



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!