Search code examples
rdataframesubscript

Using subscription to conclude from a value to another value


I have two dataframes:

x1 <- c(1,2,1,3,2,2,1,2,3,2)
y1 <- c(10,10,10,11,11,11,12,12,12,13)
df1 <- data.frame(x1,y1)

y <- c(10,11,12,13)
p <- c(0.1,0.5,0.8,0.9)
df2 <- data.frame(y,p)

What i want is some kind of subscript for df2$p, so that a value for df2$p is determined based on the input of an df1$x1-value. Rule: df1$x1 and df1$y1 form pairs of variates. The different occurrences of y1$df1 are listed in df2$y and belong to values for df2$p. For example df1$x1[1] (which is a 1) belongs to df1$y1[1] (which is a 10). As can be seen in df2, y = 10 belongs to p = 0.1. So, df1$x1[1] equals p = 0.1. Following this logic, df1$x1[2] belongs to p = 0.1, same goes for df1$x1[3]. df1$x1[4], df1$x1[5] and df1$x1[6] belong to p = 0.5. df1$x1[7], df1$x1[8] and df1$x1[9] to p = 0.8 and df1$x1[10] to p = 0.9.

Desired output should be something like:

> p[input"df1$x1[1]"]
[1] 0.1
> p[input"df1$x1[10]"]
[1] 0.9
> p[input"df1$x1[6]"]
[1] 0.5

Or

> z <- df1$x1[3]
> p[df2$y == df1$y1[df1$x1 == z]]
[1] 0.1

I am grateful for every help!


Solution

  • To incorporate @bouncyball's line into a function using dplyr:

    > library(dplyr)
    > lookup <- function(x) merge(df1, df2, by.x = 'y1', by.y = 'y') %>%
           slice(x) %>% select(p) %>% as.numeric()
    

    Here are the examples you included in the question:

    > lookup(1)
    [1] 0.1
    > lookup(10)
    [1] 0.9
    > lookup(6)
    [1] 0.5