Ayushi Bhagat
Ayushi Bhagat

Reputation: 25

How can I add a new column in my data table using dplyr function?

I have a data table with all the data related to Bank Customers.

I want to create another data table (labelled as BankCustomerAgeCategorized) with a new column added to it where the data is grouped based on the Age column in the original table.

I am using a tutorial online and after running the code provided by them, I get an error. The person is able to run the code as shown in the tutorial but I get this error. Please advise why this is happening?

BankCustomerAgeCategorized <- transform(BankCustomer, 
Generation = 
if_else(Age<22, "Z", 
if_else(Age<41, "Y", 
if_else(Age<53, "X", 
Baby Boomers""))))

Output -

Error: unexpected symbol in 
"BankCustomerAgeCategorized <- transform(BankCustomer, 
Generation = if_else(Age<22, "Z", 
if_else(Age<41, "Y", 
if_else(Age<53, "X", 
Baby Boomers"

Upvotes: 2

Views: 173

Answers (2)

Sabrina Xie
Sabrina Xie

Reputation: 108

"Baby Boomers" in the last if_else() should be in quotation marks ("") but is currently outside them.

Upvotes: 3

TarJae
TarJae

Reputation: 78917

This is for demonstration purposes only:

If you want to use dplyr package: Here is an alternative way with mutate and case_when:

library(dplyr)

BankCustomerAgeCategorized <- BankCustomer %>% 
  mutate(Generation = case_when(Age < 22 ~ "Z", 
                                Age < 41 ~ "Y", 
                                Age < 53 ~ "X", 
                                TRUE ~ "Baby Boomers"))

Upvotes: 2

Related Questions