Spruce Island Spruce Island - 1 year ago 65
R Question

Change names automatically from name to label

I have dataframe that is a subset of df and I want to swap the name for the labels.

The full list has 255 rows and I always have a subset with a variable amount of columns. How can I automate this so it does the swap automatically? Can I use a vector and matrix to solve this instead of a dataframe. I solved it but my method is clunky. I am looking for a better method to do this type of name value swap.

label <- c("Current Loan Payment", "Current Loan Payment Amount","Current Loan Payment Due Date","Fixed/Manual Loan Payment Amount","Is Manual Amortization Schedule","Re-amortize as Balloon Payment")

name <- c("Credit__Current_Loan_Payment__c" , "Credit__Current_Loan_Payment_Amount__c", "Credit__Current_Loan_Payment_Due_Date__c","Credit__Manual_Loan_Payment_Amount__c","Credit__Is_Manual_Amortization_Schedule__c","Credit__Re_amortize_as_Balloon_Payment__c" )

df <- data.frame(label, name)

df.namesToSwap <- c("Credit__Current_Loan_Payment__c", "Credit__Is_Manual_Amortization_Schedule__c" )

df.labelsIWant <- c("Current Loan Payment", "Is Manual Amortization Schedule")

Answer Source

One option is mgsub from qdap

df$name <- mgsub(df.namesToSwap, df.labelsIWant, df$name)
#[1] "Current Loan Payment"                      "Credit__Current_Loan_Payment_Amount__c"    "Credit__Current_Loan_Payment_Due_Date__c" 
#[4] "Credit__Manual_Loan_Payment_Amount__c"     "Is Manual Amortization Schedule"           "Credit__Re_amortize_as_Balloon_Payment__c"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download