Issue
This Content is from Stack Overflow. Question asked by keenan
In R, I have a dataframe df1 that looks like
name | 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$name == "a"]
and then pass t as an argument, but I do not know how to make the function access the dataframe thats name matches the value stored in t.
Solution
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))
This Question was asked in StackOverflow by keenan and Answered by jay.sf It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.