0

I have two columns. One is

V1=c(1,2,1,2,1,2)

A = data.frame(V1)

and the second dataframe is made of two variables:

V1=c(1,2) # and 
V2=c("FRUIT","SUGAR")

B = data.frame(V1, V2)

I want to add a column to V1 so that each value of V1 gets a descriptive value from B$V2 based on number matching. How I can do that, and I thank you very much.

Frank
  • 66,179
  • 8
  • 96
  • 180
GitZine
  • 445
  • 3
  • 14

2 Answers2

0

One option:

d1 <- data.frame(V1 = c(1, 2, 1, 2, 1, 2))
d1$index <- seq_len(nrow(d1))

merged <- merge(d1, d2, by = "V1")
merged <- merged[order(merged$index), c("V1", "V2")]
merged

  V1    V2
1  1 FRUIT
4  2 SUGAR
2  1 FRUIT
5  2 SUGAR
3  1 FRUIT
6  2 SUGAR
Daniel Anderson
  • 2,394
  • 13
  • 26
  • Thanks Daniel, I've tried this method, but the problem is when d1 is not ordered, the merge won't preserve the data as it was first. – GitZine Feb 26 '18 at 18:31
  • if d1 was 1,2,1,2,1 the merge will make the result look like 1,1,1,2,2 and this is not what I need in this cas. I need it to 1 FRUIT 2 SUGAR 1 FRUIT etc. – GitZine Feb 26 '18 at 18:33
  • You must have something else going on. Is V1 defined as a factor or character? If you run the code above with them ordered as you have them it still works. – Daniel Anderson Feb 26 '18 at 18:33
  • Ah... so you just want to order the data frame differently after the merge? – Daniel Anderson Feb 26 '18 at 18:34
  • Hi Daniel, I have the data unordered, and I want the merget to let it as it is, and only add the description – GitZine Feb 26 '18 at 18:36
  • Okay, in that case I'd recommend avoiding the merge altogether and going with the method @Moody_Mudskipper recommended by defining it as a factor with the levels according to `V1` and labels according to `V2`. – Daniel Anderson Feb 26 '18 at 18:38
  • if you use `dplyr::inner_join` the order will be preserved. – moodymudskipper Feb 26 '18 at 18:40
  • Thanks @Daniel, actually someone answered it. I upvoted your answer, it doesn't appear because I haven't reached the minimum amount of points :) thanks a lot for the help : ) – GitZine Feb 26 '18 at 18:41
  • No problem. I just edited my answer as another alternative. – Daniel Anderson Feb 26 '18 at 18:42
  • 1
    relevant: https://stackoverflow.com/questions/17878048/merge-two-data-frames-while-keeping-the-original-row-order – moodymudskipper Feb 26 '18 at 18:45
0

You could also use factors:

d1$V2 = factor(d1$V1,labels=d2$V2)

d1
#   V1    V2
# 1  1 FRUIT
# 2  2 SUGAR
# 3  1 FRUIT
# 4  2 SUGAR
# 5  1 FRUIT
# 6  2 SUGAR
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167