Mutate with exeptions

Hi,
I have this simple data file:

data.frame(stringsAsFactors=FALSE,
             URN = c(1042020172320, 1042020172453, 1042020172583),
      DealerCode = c("DE2331", "DE2289", "DE1672"),
   InterviewDate = c("2019-01-04 19:43:00", "2019-01-09 11:33:00",
                     "2019-01-07 16:18:00"),
              A2 = c(8, 8, 10),
              F1 = c(5, 3, 6),
              F2 = c(7, 9, 10),
              F3 = c(8, 4, 10),
              F4 = c(6, 4, 10),
              F5 = c(5, 2, 7),
              F6 = c(5, 2, 10),
           FComm = c("aaa", "bbb", "ccc"),
       AlfaModel = c("x", "y", "z")
)

I am using 2 functions below to multiply all numeric values by 10:

Option 1

result <- data.frame %>% 
  mutate_if(is.numeric, ~ .x * 10) 

and:

result <- data.frame %>% 
  mutate_at(vars(starts_with('A')), ~ .x * 10) %>% 
  mutate_at(vars(starts_with('F')), ~ .x * 10)

but they don't work :frowning:

Also, the key thing is keeping FComm and AlfaModel unchanged.

How can I do that?

Hi Slavek,

There may be a trivial solution, as it appears that you did not assign your dataset to the variable data.frame, so that your two options, which reference data.frame, do not work.

So that this (just assigning the new data frame to the variable data, then using data as a starting place for the pipe) should work

library(tidyverse)

data <- data.frame(stringsAsFactors=FALSE,
           URN = c(1042020172320, 1042020172453, 1042020172583),
           DealerCode = c("DE2331", "DE2289", "DE1672"),
           InterviewDate = c("2019-01-04 19:43:00", "2019-01-09 11:33:00",
                             "2019-01-07 16:18:00"),
           A2 = c(8, 8, 10),
           F1 = c(5, 3, 6),
           F2 = c(7, 9, 10),
           F3 = c(8, 4, 10),
           F4 = c(6, 4, 10),
           F5 = c(5, 2, 7),
           F6 = c(5, 2, 10),
           FComm = c("aaa", "bbb", "ccc"),
           AlfaModel = c("x", "y", "z")
)



result <- data %>% 
  mutate_if(is.numeric, ~ .x * 10) 


#>           URN DealerCode       InterviewDate  A2 F1  F2  F3  F4 F5  F6
#> 1 1.04202e+12     DE2331 2019-01-04 19:43:00  80 50  70  80  60 50  50
#> 2 1.04202e+12     DE2289 2019-01-09 11:33:00  80 30  90  40  40 20  20
#> 3 1.04202e+12     DE1672 2019-01-07 16:18:00 100 60 100 100 100 70 100
#>   FComm AlfaModel
#> 1   aaa         x
#> 2   bbb         y
#> 3   ccc         z

Created on 2019-10-01 by the reprex package (v0.3.0)

but if you want to get fancier and have an exact match for your columns, you could use

data %>% mutate_at(vars(matches("[A-Z]\\d")), ~.x * 10)

which matches a capital letter followed by a digit, which I think is what you are looking for.

Best wishes in data wrangling!

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.