[R] "And" condition spanning over multiple columns in data frame
Ivan Krylov
|kry|ov @end|ng |rom d|@root@org
Thu Sep 12 10:42:43 CEST 2024
В Thu, 12 Sep 2024 09:42:57 +0200
Francesca <francesca.pancotto using gmail.com> пишет:
> c10Dt <- mutate(c10Dt, exit1= ifelse(is.na(cp1) & id!=1, 1, 0))
> So, I create a new variable, called exit1, in which the program
> selects cp1, checks if it is NA, and if it is NA but also the value
> of the column "id" is not 1, then it gives back a 1, otherwise 0.
> So, what I want is that it selects all the cases in which the id=2,3,
> or 4 is not NA in the corresponding values of the matrix.
Since all your columns except the first one are the desired "cp*"
columns, you can obtain your "exit" columns in bulk:
(
c10Dt$id != 1 & # will be recycled column-wise, as we need
is.na(c10Dt[-1])
) |>
# ...and then convert back into a data.frame,
as.data.frame() |>
# rename the columns...
(\(x) setNames(x, sub('cp', 'exit', names(x))))() |>
# ...and finally attach to the original data.frame
cbind(c10Dt)
--
Best regards,
Ivan
More information about the R-help
mailing list