简体   繁体   中英

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.

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

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM