Karthik S
Karthik S

Reputation: 11596

How to use substr in dplyr Select in R

I have a dataframe from which I need to select few columns. But for one column, I just need a part of the data.

> df <- data.frame(doc_name = c('AXX_1324', 'BXX_3423', 'AXX_2343', 'BXX_3453', 'AXX_9872','AXX_9876'),
+                  Branch = c('AMM','GGM','AMM','CBB','GGM','GGM'),
+                  Revenue = rnorm(6,50,5))
> df
  doc_name Branch  Revenue
1 AXX_1324    AMM 55.95013
2 BXX_3423    GGM 43.63848
3 AXX_2343    AMM 47.31363
4 BXX_3453    CBB 47.59680
5 AXX_9872    GGM 46.94639
6 AXX_9876    GGM 45.28648
> df %>% select(doctype = substr(df$doc_name,1,3),Revenue)
Error: Unknown columns `AXX`, `BXX`, `AXX`, `BXX`, `AXX` and `AXX` 
Call `rlang::last_error()` to see a backtrace
> 

Expected output:

doctype   Revenue
AXX       55.95013
BXX       43.63848
AXX       47.31363
BXX       47.59680
AXX       46.94639
AXX       45.28648

I also tried "substring" instead of substr but got same error. Could someone let me know how to go about it.

Upvotes: 1

Views: 1775

Answers (2)

akrun
akrun

Reputation: 887691

We can use separate

library(tidyr)
library(dplyr)
df %>% 
   separate(doc_name, into = c('doctype', 'other')) %>% 
   select(doctype, Revenue)
#  doctype  Revenue
#1     AXX 50.77699
#2     BXX 47.04387
#3     AXX 39.87008
#4     BXX 54.13617
#5     AXX 46.59901
#6     AXX 34.37392

Or with str_remove in case the lengths vary

library(stringr)
df %>% 
    transmute(doctype = str_remove(doc_name, "_.*"), Revenue)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389175

Use mutate to change column values and select to select columns

library(dplyr)
df %>%
  mutate(doctype = substr(doc_name,1,3)) %>%
  select(doctype, Revenue)

#  doctype  Revenue
#1     AXX 54.25022
#2     BXX 45.37344
#3     AXX 54.46791
#4     BXX 45.29495
#5     AXX 52.69476
#6     AXX 49.09013

As mentioned by @hendrikvanb, we can also use transmute here :

df %>% transmute(doctype = substr(doc_name,1,3), Revenue)

Upvotes: 1

Related Questions