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

Time:03-10

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"

CodePudding user response:

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

CodePudding user response:

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"))
  • Related