colorlace
colorlace

Reputation: 886

Apply a function to every value in a tibble (and return a tibble)?

Straightforward usage here, but most documentation about apply/plyr/dplyr is explaining more complex operations.
I want to create a new tibble from this_tbl

> this_tbl
# A tibble: 3 x 2
      x     y
  <dbl> <dbl>
1    42   999
2     0     0
3     1     0

Such that every value > 0 is turned into a 1, and every value <= 0 is becomes a 0.

> as_tibble(apply(this_tbl,2,function(x){ifelse(x>0, 1, 0)}))
# A tibble: 3 x 2
      x     y
  <dbl> <dbl>
1     1     1
2     0     0
3     1     0

That works just fine, but is there a more elegant way to do this?

Upvotes: 2

Views: 1152

Answers (2)

James Hirschorn
James Hirschorn

Reputation: 8026

dplyr::mutate_all from @Jack Brookes solution is now superseded by the across adverb, even though there is no need for the additional functionality in this simple example:

this_tbl %>% mutate(across(, function(x) ifelse(x > 0, 1, 0)))

Upvotes: 2

Jack Brookes
Jack Brookes

Reputation: 3830

dplyr::mutate_all applies a function to all columns in a dataframe and returns the result.

this_tbl %>%
 mutate_all(function(x){ifelse(x>0, 1, 0)})

Technically, this doesn't apply the function to "every value" but to each column as a whole, which is much faster. If there is a case where you want to do it value-by-value, you could make a vectorised version of the function.

greater_than_zero <- Vectorized(function(x){
    ifelse(x > 0, 1, 0)
})

this_tbl %>%
 mutate_all(greater_than_zero)

Upvotes: 1

Related Questions