-1

I have a data.frame

df1=data.frame(f=LETTERS[1:4],v=c(1:4))
  f v
1 A 1
2 B 2
3 C 3
4 D 4

The first column is a list of factors, in which I have another data frame that houses these values, which are also factors

df2=data.frame(f=LETTERS[1:7],f2=letters[26:20])
  f f2
1 A  z
2 B  y
3 C  x
4 D  w
5 E  v
6 F  u

I am wondering how to write a function so that I can alter the values from the first column of df1 to what they map to from df2. I would like to get:

  f v
1 z 1
2 y 2
3 x 3
4 w 4

I tried a for loop with no success. Ant suggestions is greatly appreciated

Note: this is a simplified example of my work. A merge would add too many columns to work with and I don't think the extra memory storage would be very useful

frank
  • 3,036
  • 7
  • 33
  • 65
  • @A.Webb if I used a merge, my dfs would have been huge, this is just a simplification of it. – frank Mar 24 '16 at 15:33
  • 1
    @alex merge would work just fine – Pierre L Mar 24 '16 at 15:34
  • 1
    Any way you frame this question, it's been asked and answered dozens and dozens of times here. – A. Webb Mar 24 '16 at 15:41
  • if I wasn't working for so long, I would have manipulated my dfs so that I could merge... I should have some more coffee I think and finish this off. – frank Mar 24 '16 at 15:46

4 Answers4

1

We can use match

 df1$f <- df2$f2[match(df1$f, df2$f)]
 df1
 #  f v
 #1 z 1
 #2 y 2
 #3 x 3
 #4 w 4
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can use merge

merge(df1,df2,by = "f")[,c(1,3,2)]
  f f2 v
1 A  z 1
2 B  y 2
3 C  x 3
4 D  w 4
Roman
  • 17,008
  • 3
  • 36
  • 49
0
library(dplyr)
left_join(df1,df2)
adaien
  • 1,932
  • 1
  • 12
  • 26
0

You could try using the merge function to merge the two tables, then specify which columns you want to keep.

For example:

df1 <- data.frame(f=LETTERS[1:4],v=c(1:4))
df2 <- data.frame(f=LETTERS[1:7],f2=letters[26:20])

merge(df1, df2, by.x = "f")[,c("f2", "v")]

  f2 v
1  z 1
2  y 2
3  x 3
4  w 4