1

I can't figure out why this version of plyr's rename function isn't working.

I have a dataframe where I have a single column that ends up being named seq(var_slcut_trucknumber_min, var_slcut_trucknumber_max) because I made it like this:

df_metbal_slcut <- as.data.frame(seq(var_slcut_trucknumber_min,var_slcut_trucknumber_max))

The terms var_slcut_trucknumber_min and var_slcut_trucknumber_max are defined as the min and max of another column.

However, when trying to rename it by the following code,

var_temp <- names(df_metbal_slcut)
df_metbal_slcut <- rename(df_metbal_slcut, c(var_temp="trucknumber"))

I get an error as follows:

The following `from` values were not present in `x`: var_temp

I don't understand why. I know that I can easily do this as colnames(df_metbal_slcut)[1] <- "trucknumber", but I'm an R n00b, and I was looking at a data manipulation tutorial that said that learning plyr was the way to go, so here I am stuck on this.

Reuben Mathew
  • 598
  • 4
  • 22

1 Answers1

1

Try this instead:

df_metbal_slcut <- rename(df_metbal_slcut, setNames("trucknumber",var_temp))

The reason it wasn't working was that c(var_temp = "trucknumber") creates a named vector with the name var_temp, which is not what you were intending. When creating named objects using the tag = value syntax, R won't evaluate variables. It assumes that you literally want the name to be var_temp.

More broadly, it might make sense to name the column more sensibly when initially creating the data frame again using setNames.

joran
  • 169,992
  • 32
  • 429
  • 468
  • Thanks for the heads up about setNames. I tried it as follows and it works. `setNames(df_metbal_slcut, c("trucknumber"))` Thank you kindly for looking at my problem. I will "check" your answer in 2 minutes when SO allows me to do so. – Reuben Mathew Jun 30 '14 at 14:50
  • A thousand apologies, but it seems that `setNames(df_metbal_slcut, c("trucknumber"))` didn't actually change the name of the column of `df_metbal_slcut`. When I call up `df_metbal_slcut` with `View(df_metbal_slcut)`, I get the old name for the first column again. Is `setNames` meant to be used within a plyr function and not on its own? – Reuben Mathew Jun 30 '14 at 14:57
  • @ReubenMathew Like most anything in R, you have to assign the result to something. `setNames` doesn't modify anything in place. e.g. `df_metbal_slcut <- setnames(...)`. – joran Jun 30 '14 at 14:58
  • OK. I was confused because using `setNames` brought up the `df_metbal_slcut` dataframe in the console with the first column named to `trucknumber`, but as you said, it wasn't assigned to anything. I will watch for that in the future. Thank you again for taking the time to answer my questions. It's much appreciated. – Reuben Mathew Jun 30 '14 at 15:00