This is something that I come across fairly often and this is the solution that I typically land on. I'm wondering if anyone has suggestions on a less verbose way to accomplish this task. Here I create an example dataframe that contains three columns. One of these columns is a parameter code rather than a parameter name.
Second I create an example of a reference dataframe that contains unique parameter codes and the associated parameter names.
My solution has been to use a 'for' loop to match the parameter name from real_param_names
with the associated parameter codes in dat
. I have tried to use match()
and replace
but haven't quite found a way that those work. None of the examples I've come across in old questions have quite hit the mark either but would be happily referred to one that does. Thank in advance.
dat <- data.frame(site = c(1,1,2,2,3,3,4,4),
param_code = c('a','b','c','d','a','b','c','d'),
param_name = NA)
dat
real_param_names <- data.frame(param_code = c('a','b','c','d'),
param_name = c('gold', 'silver', 'mercury', 'lead'))
real_param_names
for (i in unique(dat$param_code)) {
dat$param_name[dat$param_code==i] <- real_param_names$param_name[real_param_names$param_code==i]
}
dat