I'm using a for loop to create a set of new columns in an R dataframe but the in the output the original columns are duplicated, with the addition of the dataframe name as a suffix, and the new columns also have this suffix, which I don't want. I simply want the new output to be the same as the original dataframe, but with a set of new columns containing the new calculations. How do I achieve this? Details below:
These are the columns of the original dataframe: Area; SR_2005;SR_2006;SR_2007;SR_2008;xnull_SR_2005;xnull_SR_2006;xnull_SR_2007;xnull_SR_2008
I then wanted to add a series of new fields to this dataframe, where each ‘SR’ column was divided by its corresponding ‘xnull_SR’ column (e.g. SR_2005/ xnull_SR_2005); each of these new fields would be prefixed with “p_”, e.g. “p_2005”). Here is the code I've used:
for (j in 2005:2019)
{field = paste("p_", j, sep = "")
restab1 <- within(restab1, restab1[[field]] <- get(paste("SR_",j, sep = ""))/ get(paste("xnull_SR_",j, sep = "")))
}
What I hoped for is that I would just get the original data fields with the new fields (“p_2005”, “p_2006” etc) added. Instead of this I do indeed get the new fields, but they are all prefixed with the name of the dataframe (e.g. restab1.p_2005) and as well as that the original fields are repeated, once just with the field name (e.g. “SR_2005”) and once with the dataframe prefix (e.g. “restab1.SR_2005”). Therefore, these are the field names in the changed dataframe:
area SR_2005 SR_2006 SR_2007 SR_2008 xnull_SR_2005 xnull_SR_2006 xnull_SR_2007 xnull_SR_2008 restab1.area restab1.SR_2005 restab1.SR_2006 restab1.SR_2007 restab1.SR_2008 restab1.xnull_SR_2005 restab1.xnull_SR_2006 restab1.xnull_SR_2007 restab1.xnull_SR_2008 restab1.p_2005 restab1.p_2006 restab1.p_2007 restab1.p_2008
The calculations in the new fields (restab1.p_2005 restab1.p_2006 etc.) are correct but I just want the dataframe to contain the old and new field names once, and without the "restab1" prefix. How do I achieve this?