HelpMe
HelpMe

Reputation: 97

Computing ratio between elements with dplyr in R data frame?

Suppose we have a data frame (df) like this:

a b
1 2
2 4
3 6

If I want to compute the ratio of each element in vectors a and b and assign to variable c, we'd do this:

c <- df$a / df$b

However, I was wondering how the same thing could be done using the dplyr package? I.e. are there any ways that this can be achieved using functions from dplyr?

Upvotes: 0

Views: 171

Answers (3)

akrun
akrun

Reputation: 887078

An option with invoke

library(dplyr)
library(purrr)
df %>% 
   mutate(c = invoke('/', .))

-output

#  a b   c
#1 1 2 0.5
#2 2 4 0.5
#3 3 6 0.5

data

df <- data.frame(a = c(1,2,3), b= c(2,4,6))

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101257

Maybe you can try the code below

df %>%
  mutate(c = do.call("/", .))

or

df %>%
  mutate(c = Reduce("/", .))

or

df %>%
  mutate(c = a/b)

Upvotes: 0

AlSub
AlSub

Reputation: 1155

You can use mutate function from dplyr library:

df <- data.frame(a = c(1,2,3), b= c(2,4,6))

library(dplyr)

df <- df %>%
           dplyr::mutate(c = a/b)

Console output:

  a b   c
1 1 2 0.5
2 2 4 0.5
3 3 6 0.5

Upvotes: 0

Related Questions