简体   繁体   中英

Multiply specific values in dataframe

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?

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 ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM