Bio_farmer
Bio_farmer

Reputation: 159

How to calculate the value based on the other value?

I have a data frame, for example:

ID category value1  value2
1    A         2      5
1    A         3      6
1    A         5      7
1    B         6   **12**
2    A         1      3
2    A         2      5
2    B         5   **10**

Now I want to add a new column to calculate the percentage. For each ID, the way of calculation is to use each value1 of category A to divide the value2 of category B. For value1 of category B, it divides value2 of category B directly. The expected result likes:

ID category value1 value2 percentage
1    A        2      5     0.17
1    A        3      6     0.25
1    A        5      7     0.42
1    B        6    **12**  0.50
2    A        1      3     0.10
2    A        2      5     0.20
2    B        5    **10**  0.50

Thank you very much.

Upvotes: 0

Views: 109

Answers (1)

Chris
Chris

Reputation: 3986

Using dplyr you could do something like this, assuming there is only one category B value for each of your IDs as per your example:

library(dplyr)

df1 <- tibble(
      ID = c(1,1,1,1,2,2,2),
      category =c('A', 'A', 'A','B','A','A','B'),
      value1 = c(2,3,5,6,1,2,5),
      value2 = c(5,6,7,12,3,5,10)
    )


df1 %>%
  group_by(ID) %>%
  mutate(percentage = value1 / value2[category == 'B'])


# # A tibble: 7 x 5
# # Groups:   ID [2]
#      ID category   value1 value2 percentage
#     <dbl> <chr>     <dbl>  <dbl>    <dbl>
# 1     1 A             2      5      0.167
# 2     1 A             3      6      0.25 
# 3     1 A             5      7      0.417
# 4     1 B             6     12      0.5  
# 5     2 A             1      3      0.1  
# 6     2 A             2      5      0.2  
# 7     2 B             5     10      0.5  

Upvotes: 1

Related Questions