I have a tibble. I need to add a new column in which each value is a function of the corresponding values in several other columns. Here is an example:
library(tibble)
tmp <- tribble(
~ID, ~x1, ~x2,
1, "200", NA,
2, "300", "400")
I want to add a new column, new
, that is TRUE
if and only if any of the corresponding values in x1
and x2
start with "3". That is, I want
# A tibble: 2 x 4
ID x1 x2 new
<dbl> <chr> <chr> <lgl>
1 1 200 <NA> NA
2 2 300 400 TRUE
In this example, new
is a function of only x1
and x2
. But there may be many of these "x" columns, and I won't always be able to write out their names. They will always start with "x", though, so this is one solution:
tmp %>%
mutate(
new = select(., starts_with("x")) %>%
apply(., 1, function (x) any(substr(x, 1, 1)=="3"))
)
But this solution is pretty clunky. Is there a more elegant way?
There are many related questions on Stack Overflow, but they generally speak to cases in which (a) the names of all columns in the original dataset are known and can be written out, or (b) the new
variable is a function of all other columns in the data frame. (Here is one example.)