[英]Generate a vector: when values in one vector match another vector, input the value of another vector at the same position in R
I am trying to create a new vector in a dataframe in R, based on vectors in another dataframe. 我正在尝试根据另一个数据帧中的向量在R中的数据帧中创建一个新向量。
I have a dataframe which contains outlet numbers. 我有一个包含插座号的数据框。 And another dataframe (a concordance table) which shows which outlet name corresponds with which outlet number.
另一个数据框(一致性表)显示哪个出口名称与哪个出口编号相对应。 Using the concordance table, I want to find the names of the outlets for each relevant outlet number in my first dataframe, and put these into the first dataframe as a new vector.
使用一致性表,我想在我的第一个数据框中找到每个相关插座编号的插座名称,并将它们作为新矢量放入第一个数据框中。
Here is an example of my data 这是我的数据的一个例子
outlet <- rep(1:26)
outletname <- letters[1:26]
concordance <- data.frame(outlet, outletname)
df1 <- data.frame(outlet)
What I want to do, is say to R when df1$outlet == concordance$outlet
return the value for concordance$outletname
at the same position within the vector of concordance$outlet
我想做的是,当
df1$outlet == concordance$outlet
返回concordance$outletname
在concordance$outlet
向量内相同位置的值时,对R说
Does anyone know how to do this? 有谁知道如何做到这一点? Many thanks for your help.
非常感谢您的帮助。
In your example data df1$outlet
is already equal to concordance$outlet
at all points. 在您的示例数据中,
df1$outlet
concordance$outlet
在所有点上都已经等于concordance$outlet
。 I assume you want something that works even when that's not true, so let's scramble the data first to check that what we do works in all cases: 我假设您希望某些东西即使在不正确的情况下也能正常工作,因此让我们先对数据进行加扰以检查在所有情况下我们所做的工作是否有效:
set.seed(123)
df1 = df1[sample(1:nrow(df1)), , drop = FALSE]
Then you can merge in the outlet names: 然后,您可以合并出口名称:
df1 = merge(df1, concordance, by="outlet", sort = FALSE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.