A clean solution to avoid selection errors

I'm trying to do something like

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

This works well if there are lines matching the selection.

If not, I get an error

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

However, my code is designed in such a way that a match is not possible.

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

+4
source share
2 answers

Using

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

those. make an assignment to the data frame, considering it as a two-dimensional object, and not as a list.

+12
source

Use dplyr :

 d %>% dplyr::mutate(n = ifelse(c == 'a', 5, n)) 
0
source

Source: https://habr.com/ru/post/1486217/


All Articles