Conditional calculations for rows in dataframe R

in my dataset in the column "new" I would like to do the following:
if the percentage is bigger than 100% I would like to subtract that percentage from 200%, e.g. if the value is 120% I want the new value in the row to be 200%-120% which would be 80%. How can I achieve that? Thank you!

jointdataset1 <- structure(list(group = c("Interests", "Interests", "Interests", 
"Interests", "Interests", "Interests", "Interests", "Interests", 
"Interests", "Interests", "Interests", "Interests"), mean_name = c("Administrating processes", 
"Analytical", "Art and Culture", "Commercial activities", "Creative", 
"Helping/supporting", "Leading", "Networking", "Physical", "Practical", 
"Technical", "Transforming Processes"), means.x = c(4, 4, 1, 
4, 3, 3, 3, 3, 3, 6, 6, 1), means.y = c(4, 5.5, 1, 5, 3, 4, 4.5, 
3.5, 2.5, 5.5, 6.5, 3), new = c("100.0%", "72.7%", "100.0%", 
"80.0%", "100.0%", "75.0%", "66.7%", "85.7%", "120.0%", "109.1%", 
"92.3%", "33.3%")), class = "data.frame", row.names = c(NA, -12L
))

>Solution :

If you want the "new" column to still have the % sign, you can do the following:

library(dplyr)
jointdataset1 %>%
  mutate(value = as.numeric(sub("\\%.*", "", new)),
         new_value = ifelse(value > 100, 200 - value, value),
         new = paste0(new_value,'%')) %>%
  dplyr::select(c(-value, -new_value))

Output:

       group                mean_name means.x means.y   new
1  Interests Administrating processes       4     4.0  100%
2  Interests               Analytical       4     5.5 72.7%
3  Interests          Art and Culture       1     1.0  100%
4  Interests    Commercial activities       4     5.0   80%
5  Interests                 Creative       3     3.0  100%
6  Interests       Helping/supporting       3     4.0   75%
7  Interests                  Leading       3     4.5 66.7%
8  Interests               Networking       3     3.5 85.7%
9  Interests                 Physical       3     2.5   80%
10 Interests                Practical       6     5.5 90.9%
11 Interests                Technical       6     6.5 92.3%
12 Interests   Transforming Processes       1     3.0 33.3%

Leave a Reply