1

I am trying to make some sort of loop using R, where the loop searches for a spesific value from a column in df1 in a column in another dataframe(df2), and returns a value from the next column if the value is found in df3.

A simple example of df1, df2 and the wanted result in df3 is illustrated below. I would greatly appreciate some help with this, as i am not very experienced in R and thus have a hard time figuring out loops..

> df1
Col1
A
B
C
D
E
F
G
> df2
Col1    Val1
A       1
B       3
B       5
H       3
E       7
G       2
K       9
G       1
> df3
Col1   Val1
A      1
B      3
B      5
E      7
G      2
G      1
signe
  • 37
  • 4

2 Answers2

2

in base R:

df1 <- read.table(h=T, text="
Col1
A
B
C
D
E
F
G")
df2 <- read.table(h=T, text="
Col1    Val1
A       1
B       3
B       5
H       3
E       7
G       2
K       9
G       1")

merge(df1, df2)
#>   Col1 Val1
#> 1    A    1
#> 2    B    3
#> 3    B    5
#> 4    E    7
#> 5    G    2
#> 6    G    1

Created on 2020-09-28 by the reprex package (v0.3.0)

You might want to set the argument all.x = TRUE to do a left join.

moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
1

This type of thing is a lot easier with tidyverse/dplyr...

library(dplyr)

df1 <-
  tribble(
    ~Col1,
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G"
  )

df2 <-
  tribble(
    ~Col1, ~Val1,
    "A",   1,
    "B",   3,
    "B",   5,
    "H",   3,
    "E",   7,
    "G",   2,
    "K",   9,
    "G",   1
  )

df1 %>% inner_join(df2)
#> Joining, by = "Col1"
#> # A tibble: 6 x 2
#>   Col1   Val1
#>   <chr> <dbl>
#> 1 A         1
#> 2 B         3
#> 3 B         5
#> 4 E         7
#> 5 G         2
#> 6 G         1
CJ Yetman
  • 8,373
  • 2
  • 24
  • 56