Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean solution to avoid error caused by selection

Tags:

r

I try to do something like

df[<very-long-and-complicated-selection>,]$foo <- "bar"

This works well, if there are rows matching the selection.

If not I get an error message

Error in $<-.data.frame(*tmp*, "foo", value = "bar") :
replacement has 1 row, data has 0

However, my code is designed in a way, where no matching is possible.

Is there a clean, short and easy solution to avoid these (and only these) errors?

like image 627
speendo Avatar asked Dec 15 '22 09:12

speendo


1 Answers

Use

df[<very-long-and-complicated-selection>, "foo"] <- "bar"

ie, make the assignment into the dataframe treating it as a 2-dimensional object, rather than as a list.

like image 151
Hong Ooi Avatar answered Dec 26 '22 01:12

Hong Ooi