Mutate with 2 existing variables

Hi,

I am trying to create a new variable through mutate. I have to select two existing variables from dataset , one variable named total_hit should have values above 40 and second variable total_work should have values above 80. These observations should be put in a new variable total_hit_work . For this i use the below formula but it shows error;


data_new<-data %>%
  select(total_hit, total_work) %>%
  filter(total_hit>"40", total_work>"80")

data_new<-data %>%
  mutate(total_hit_work=parsenumber(total_hit>40 & total_work>80))

It shows error in showing the observations in the new variable. How to correct the code. Need help! Thanks

No quotes for numbers
filter(total_hit>40, total_work>80)

Hi pathos,

I have removed the quoted from number but it still shows below error. Thanks

Error: Problem with mutate() column total_hit_work. i total_hit_work = parsenumber(total_hit > 40 & total_work > 80). x could not find function "parsenumber" Run rlang::last_error() to see where the error occurred.

This is a logical comparison so the result would be a boolean (TRUE or FALSE), if you want to get 0 or 1 instead use as.numeric(), see this example.

library(dplyr)

sample_df <- data.frame(
    total_hit = 35:45,
    total_work = 75:85
)

sample_df %>% 
    mutate(total_hit_work = as.numeric(total_hit > 40 & total_work > 80))
#>    total_hit total_work total_hit_work
#> 1         35         75              0
#> 2         36         76              0
#> 3         37         77              0
#> 4         38         78              0
#> 5         39         79              0
#> 6         40         80              0
#> 7         41         81              1
#> 8         42         82              1
#> 9         43         83              1
#> 10        44         84              1
#> 11        45         85              1

Created on 2021-08-23 by the reprex package (v2.0.1)

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

Hi andresrcs,

Thanks for the explanation. I was also confused that why it's showing TRUE and False when I run the code without the parse_number in mutate. Now, with as.numeric it is showing it as a new variable with values of 2 other variables in the form of number. I hope they will accept this solution as it works.

Thanks heaps.

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.