I often use R to create tables that will form part of a publication. For example, I might have a table of coefficients or a correlation matrix. When creating such tables, I often have the R variable names stored in a data.frame. However, for the publication table I need to replace the R variable names with publishable variable labels. I often have these stored in some meta-data file.
This post talks about how to replace variable names with a label.
Assume that we have a data frame that represent the table with R variables
c, and I want to replace these variable names with the labels in the meta-data data.frame called
foo_table <- data.frame(variable=c('a','b', 'c'), mean=c(1,2,3), sd=c(5,4,3)) foo_labels <- data.frame(variable=c('a','b', 'c'), label=c('Apple', 'Banana', 'Carrot'))
So the end result should look something like
data.frame(variable=c('Apple','Banana', 'Carrot'), mean=c(1,2,3), sd=c(5,4,3))
The following code appears to work:
foo_table$variable <- foo_labels[match(foo_table$variable, foo_labels$variable), 'label']
match returns the position of the variable name in the label metadata file. This position is used as an index for the meta data data.frame, which in turn is assigned to the old variable name.
Anyway, I’ve tested this here. I don’t yet know how robust this approach is.