Home > other >  In R dataframe, how to change numeric variable in easy way
In R dataframe, how to change numeric variable in easy way

Time:10-21

In R dataframe, I want to change the numeric variables to opposite number (multiply -1 ) where category equal 'a' or 'b'. Currently, the code is little longer, is the any other way for this ? Thanks!

test_data <- data.frame(category=c("a","b","x","a","b","c","d"),
           amount_local=c(10,30,52,5,67,5,20),
           amount_usd=c(1,3,5,7,8,3,4))

test_data$amount_local[test_data$category %in% c('a','b') ] <- test_data$amount_local[test_data$category %in% c('a','b') ]*-1

test_data$amount_usd[test_data$category %in% c('a','b') ] <- test_data$amount_usd[test_data$category %in% c('a','b') ]*-1

CodePudding user response:

Does this work:

library(dplyr)
test_data %>% mutate(across(starts_with('amount'), ~ ifelse(category %in% c('a','b'), . * -1, .)))
  category amount_local amount_usd
1        a          -10         -1
2        b          -30         -3
3        x           52          5
4        a           -5         -7
5        b          -67         -8
6        c            5          3
7        d           20          4

CodePudding user response:

You can multiply multiple columns together. To avoid repeating the condition you can save it in a variable.

inds <- test_data$category %in% c('a','b')
test_data[inds, -1] <- test_data[inds, -1] * -1

#  category amount_local amount_usd
#1        a          -10         -1
#2        b          -30         -3
#3        x           52          5
#4        a           -5         -7
#5        b          -67         -8
#6        c            5          3
#7        d           20          4

CodePudding user response:

You can select multiple columns at once if the conditions are the same.

test_data[test_data$category %in% c('a','b'), c('amount_local', 'amount_usd')] <- test_data[test_data$category %in% c('a','b'), c('amount_local', 'amount_usd')] * -1

Also plenty of dplyr solutions that should be pretty clear if you have a little read.

  • Related