1
votes

I have a data frame ("tidydataset") that looks like this:

  Block        Group_code   avg    count
  1            Q.DB1_01     1.53   456   
  1            Q.DB1_02     1.63   456   
  1            Q.DB1_03     1.29   456    
  1            Q.DB2_01     2.11   456    
  1            Q.DB2_02     1.43   456    
  1            Q.DB2_03     1.61   456    

I am trying to create a new variable that takes the 5th character of "Group_code" and then recodes it according to the following levels: 1 = Phone, 2 = Tablet, 3 = PC, etc.

This is my code so far:

tidydataset %>%
  mutate(Group_name = as.numeric(substr(Group_code, start=5, stop=5))) %>%
  mutate(Group_name = recode(Group_name, `1` = "Phone", `2` = "Tablet", `3` = 
     "PC"))

This throws up an error message: "Error in mutate_impl(.data,dots) : Evaluation error: unused arguments (1 = "Phone", 2 = "Tablet", 3 = "PC").

Any idea where I'm going wrong? ALso is there any way to combine those two mutate statements into one, and write the new column to the data frame?

Thanks

2
Seems to work when I run it. Can't replicate the error. Try to clean your working space and run it again. - AntoniosK
Also, in the data you posted it seems that you already have the Group_name column. - AntoniosK
Thanks @AntoniosK but its still not working despite running rm(list=ls()). Any other ideas? - stixmcvix
Maybe it's a package or R version thing? Can you restart R and reload your packages before you run this example? - AntoniosK

2 Answers

1
votes

You can just use a base R switch statement in mutate:

library(dplyr)
tidydataset %>%
    rowwise() %>%
    mutate(Group_name = switch(substr(Group_code, start=5, stop=5),
                               '1' = "Phone",
                               '2' = "Tablet",
                               '3' = "PC"
    ))

Source: local data frame [6 x 5]
Groups: <by row>

# A tibble: 6 x 5
  Block Group_code   avg count Group_name
  <int> <chr>      <dbl> <int> <chr>     
1     1 Q.DB1_01    1.53   456 Phone     
2     1 Q.DB1_02    1.63   456 Phone     
3     1 Q.DB1_03    1.29   456 Phone     
4     1 Q.DB2_01    2.11   456 Tablet    
5     1 Q.DB2_02    1.43   456 Tablet    
6     1 Q.DB2_03    1.61   456 Tablet    

You want to remove the as.numeric, since by keeping Group_code as a character lets you match the the value to output using = as above.

0
votes

An alternative

Group_name = as.numeric(substr(Group_code, start=5, stop=5))
Group_name[Group_name==1] = "Phone"
Group_name[Group_name==2] = "Tablet"
Group_name[Group_name==3] = "PC"

cbind(tidydataset, Group_name)

#  Block Group_code  avg count Group_name
#1     1   Q.DB1_01 1.53   456      Phone
#2     1   Q.DB1_02 1.63   456      Phone
#3     1   Q.DB1_03 1.29   456      Phone
#4     1   Q.DB2_01 2.11   456     Tablet
#5     1   Q.DB2_02 1.43   456     Tablet
#6     1   Q.DB2_03 1.61   456     Tablet