Reputation: 215
I have a dataframe and I would like to multiply specific values in one column by minus 1.
I can filter my data set, multiply the column I need by -1 and then join the data back to the original dataframe but this seems ridiculously inelegant. I'm wondering if there's a better solution I'm overlooking?
This is my dataframe:
input = structure(list(V1 = c("Sales", "Sales", "Sales", "Sales", "Sales",
"Sales", "Sales", "Sales", "Sales", "Sales", "Sales", "Sales",
"Sales", "Sales", "Sales", "Sales", "Sales", "Sales", "Sales",
"Sales"), V2 = c("Frank", "John", "Bill", "Bob", "Toby", "Sam",
"Michael", "Nicole", "Dimitri", "Gene", "Keiran", "Dave", "Lucy",
"Claire", "Sarah", "Virginia", "Bob", "Nicole", "John", "Frank"
), V3 = c("Australia", "Australia", "Australia", "Australia",
"NZ", "NZ", "NZ", "NZ", "Germany", "Germany", "Germany", "Germany",
"India", "India", "India", "India", "USA", "USA", "USA", "USA"
), V4 = c(218L, 140L, 374L, 146L, 317L, 232L, 60L, 177L, 50L,
292L, 255L, 17L, 193L, 364L, 77L, 27L, 330L, 337L, 298L, 361L
)), class = "data.frame", row.names = c(NA, -20L))
And these are the V2 rows where I'd like to multiply the V4 column value by "-1"
inverse = c("Frank", "John", "Toby", "Sam", "Lucy", "Claire")
This is the output I get if I filter by V2 and then join the new results:
structure(list(V1 = c("Sales", "Sales", "Sales", "Sales", "Sales",
"Sales", "Sales", "Sales", "Sales", "Sales", "Sales", "Sales",
"Sales", "Sales", "Sales", "Sales", "Sales", "Sales", "Sales",
"Sales"), V2 = c("Frank", "John", "Bill", "Bob", "Toby", "Sam",
"Michael", "Nicole", "Dimitri", "Gene", "Keiran", "Dave", "Lucy",
"Claire", "Sarah", "Virginia", "Bob", "Nicole", "John", "Frank"
), V3 = c("Australia", "Australia", "Australia", "Australia",
"NZ", "NZ", "NZ", "NZ", "Germany", "Germany", "Germany", "Germany",
"India", "India", "India", "India", "USA", "USA", "USA", "USA"
), V4 = c(-218L, -140L, 374L, 146L, -317L, -232L, 60L, 177L,
50L, 292L, 255L, 17L, -193L, -364L, 77L, 27L, 330L, 337L, -298L,
-361L)), class = "data.frame", row.names = c(NA, -20L))
I'm curious if there's a better function I could use to achieve the same results?
Upvotes: 0
Views: 42
Reputation: 3639
Try mutate combined with if_else
library(tidyverse)
inverse = c("Frank", "John", "Toby", "Sam", "Lucy", "Claire")
input %>%
mutate(V4 = if_else(V2 %in% inverse,-V4, V4 ))
Upvotes: 1