0

I have a dataframe where the column names are values (although, they are actually text eg Value_1, Value_2 etc). I also have a table with the values (Value_1 etc) and text column names (Corn, Soy etc). I would like to match the value columns in these two dataframes and replace the Value_1, Value_2 column names with the text name. I'm guessing there's a way to do this using match, but I'm new to R and can not figure it out.

So, I have:

Site Value_1  Value _2  Value_3
A
B
C 

and...

Value    Name
Value_1  Corn
Value_2  Soy
Value_3  Hay

and I want

Site Corn  Soy  Hay
A
B
C 

Again, I am new to R so please explain it to me like I'm an idiot. I appreciate the help!

Grace
  • 1
  • Maybe turn df2 into a named vector, then change the names of df1. `myVec <- setNames(as.character(df2$value), as.character(df2$name))` then `names(df1)[myVec] <- names(myVec)`. The `names(df1)[myVec]` portion will make sure that the names of df1 are placed in the proper order for the assignment. – lmo Jan 31 '17 at 16:57
  • If you use library(data.table), you can map values using code like this: `DT[, new_var := mapvalues(DT[, var_to_match], from = Old_vec_of_values, to = new_vec_of_values)]`, where "var_to_match" is the column with the values you want to replace ("Value"), "Old_vec_of_values" is a vector you create with the unique values of "Value", and "new_vec_of_values" is a vector you create with the unique values of "Names". The vectors of values and names need to be in mapped order. This particular code creates a new variable, but you could just replace your old variable instead. – juliamm2011 Jan 31 '17 at 17:43

0 Answers0