1

Add a new data frame column with a value in a list1, matching a column value in data frame to the value that is present in another list list2. Both list1 and list2 are of same length

I can do this using for loop but I want an efficient way to do this. Any suggestion would be helpful.

DF1 <- data.frame(c1=rep(1:3, 2), c2=rep(c(0.1, 0.2, 0.3), 2))
list1 <- c(1, 2, 3)
list2 <- c(0.6, 0.7, 0.8)

This is the input

DF1
  c1  c2
1  1 0.1
2  2 0.2
3  3 0.3
4  1 0.1
5  2 0.2
6  3 0.3

This is what I expect Should create a new column c3(with the value in the list2) matching values in column(c1) to the value in the list1

DF1
  c1  c2 c3
1  1 0.1 0.6
2  2 0.2 0.7
3  3 0.3 0.8
4  1 0.1 0.6
5  2 0.2 0.7
6  3 0.3 0.8
Sotos
  • 51,121
  • 6
  • 32
  • 66
Shobha
  • 141
  • 1
  • 7

2 Answers2

1

You could make a data frame to lookup e.g.

DF2 <- data.frame(c1 = 1:3, c3 = c(0.6, 0.7, 0.8))

and then join on with either merge or dplyr::left_join. For example:

merge(DF1, DF2, by.x = "c1", by.y = "c1")

or

left_join(DF1, DF2, by = "c1")
cwthom
  • 393
  • 1
  • 13
0

You can use match, i.e.

list2[match(DF1$c1, list1)]
#[1] 0.6 0.7 0.8 0.6 0.7 0.8
Sotos
  • 51,121
  • 6
  • 32
  • 66