Skip to content
Advertisement

Joining two dataframes which have variable names as values in R / SQL

I am using R

I am trying to join two which look like this:

 
DF1: 

Name Species Value Variable_id 
Jake Human   99    1
Jake Human   20    2
Mike Lizard  12    1
Mike Lizard  30    2


DF2:

Variable_id Varible_name
1           Height
2           Age

And I need it in the form of

Name Species Height Age
Jake Human   99     20
Mike Lizard  12     30

Advertisement

Answer

library(dplyr)
library(tidyr)

DF1 %>% left_join(DF2) %>%
  select(-Variable_id) %>%
  pivot_wider(names_from = Varible_name, values_from = Value)
# Joining, by = "Variable_id"
# # A tibble: 2 x 4
#   Name  Species Height   Age
#   <chr> <chr>    <int> <int>
# 1 Jake  Human       99    20
# 2 Mike  Lizard      12    30

Using this data:

DF1 = read.table(text = 'Name Species Value Variable_id 
Jake Human   99    1
Jake Human   20    2
Mike Lizard  12    1
Mike Lizard  30    2', header = T)

DF2 = read.table(text = "Variable_id Varible_name
1           Height
2           Age", header = TRUE)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement