Use contents of variable as name of dataframe for a function in r

Viewed 18

In R, I have a dataframe df1 that looks like

variable location
a T1
b T2
c T1

location corresponds to the name of another dataframe. I am trying to create a function to update the contents of this dataframe (in this case either T1 or T2).

My approach so far is as follows t <- df1$location[df1$variable == "a"] this sets t = "T1" now I would like to create a function doesSomething <- function(df) and pass the value stored in t as an argument to the function. Ideally calling doesSomething(t) would allow me modify the dataframe T1 within the function.

1 Answers

Using match.

transform(dat, value=cont$value[match(location, cont$loc)])
#   location name value
# 1       T1    a     1
# 2       T1    c     1
# 3       T2    b     2

Or merge.

merge(dat, cont, by.x='location', by.y='loc')
#   location name value
# 1       T1    a     1
# 2       T1    c     1
# 3       T2    b     2

Data:

dat <- structure(list(name = c("a", "b", "c"), location = c("T1", "T2", 
"T1")), class = "data.frame", row.names = c(NA, -3L))

cont <- structure(list(loc = c("T1", "T2"), value = 1:2), class = "data.frame", row.names = c(NA, 
-2L))
Related