1

How can I merge dataset x and dataset y, where dataset y is a 'category reference', so I want to merge these two dataset, and use dataset y as many time as needed. so like:

dataset x: 
apple 3 
apple 4
banana 5
banana 6
apple 5
carrot 4
apple 3 
carrot 3

dataset y:
apple fruit
banana fruit
carrot vegetable

result I want:

apple 3 fruit
apple 4 fruit
banana 5 fruit
banana 6 fruit
apple 5 fruit
carrot 4 vegetable
apple 3 fruit
carrot 3 fruit
Martin Gal
  • 16,640
  • 5
  • 21
  • 39
Yuman Wu
  • 11
  • 1
  • 1
    Please share a reproducible sample of each of your data sets by `dput(head(data))` so you will have better chances of getting relevant answers. – Anoushiravan R Jul 11 '21 at 17:19

2 Answers2

1

You could use left_join from dplyr:

library(tidyverse)

# Reproducing your data
x <- tibble(
  fruit = c("apple", "apple", "banana", "banana", "apple", "carrot", "apple", "carrot"),
  count = c(3,4,5,6,5,4,3,3)
)

y <- tibble(
  fruit = c("apple", "banana", "carrot"),
  type = c("fruit", "fruit", "vegetable")
)

left_join(x, y, by = "fruit")

Output:

# A tibble: 8 x 3
  fruit  count type     
  <chr>  <dbl> <chr>    
1 apple      3 fruit    
2 apple      4 fruit    
3 banana     5 fruit    
4 banana     6 fruit    
5 apple      5 fruit    
6 carrot     4 vegetable
7 apple      3 fruit    
8 carrot     3 vegetable
Rory S
  • 1,278
  • 5
  • 17
0

In base R you could use merge.

fruit <- c("apple", "apple", "banana", "banana", "apple", "carrot", "apple", 
count <- c(3,4,5,6,5,4,3,3)"carrot")
x <- data.frame(fruit, count)

fruit <- c("apple", "banana", "carrot")
type <- c("fruit", "fruit", "vegetable")
y <- data.frame(fruit, type)

merge(x, y, by = "fruit")
norie
  • 9,609
  • 2
  • 11
  • 18