Home > Enterprise >  Join list to dataframe in R
Join list to dataframe in R

Time:01-16

I have the following dataframe df and list l (dput below):

> df
  group value
1     A     1
2     B     2
3     C     3
> l
$A
[1] 999

$B
[1] 55

I would like to join the values of the list to the dataframe based on the names in the list with the group variable of the dataframe and call it "value_l". The expected output should look like this:

  group value value_l
1     A     1     999
2     B     2      55
3     C     3      NA

So I was wondering if anyone knows how to join a list to a dataframe based on their names?


dput df and l:

df <- structure(list(group = c("A", "B", "C"), value = c(1, 2, 3)), class = "data.frame", row.names = c(NA, 
-3L))
l <- list(A = 999, B = 55)

CodePudding user response:

You can do:

library(tidyverse)

l |> 
  as.data.frame() |> 
  pivot_longer(cols      = everything(),
               names_to  = "group",
               values_to = "value_1") |> 
  left_join(x  = df,
            y  = _,
            by = "group")

which gives:

  group value value_1
1     A     1     999
2     B     2      55
3     C     3      NA

CodePudding user response:

You can use match.

df$value_l <- l[match(df$group, names(l))]

df
#  group value value_l
#1     A     1     999
#2     B     2      55
#3     C     3    NULL

Or (thanks to @G. Grothendieck for the comment) to give NAs instead of NULLs.

df$value_l <- unlist(l)[match(df$group, names(l))]

df
#  group value value_l
#1     A     1     999
#2     B     2      55
#3     C     3      NA

CodePudding user response:

Update:

Maybe this one:

library(dplyr)

stack(unlist(l)) %>% 
  full_join(df, by=c("ind"="group"))

  values ind value
1    999   A     1
2     55   B     2
3     NA   C     3 

First answer: Slightly different:

library(dplyr)
library(tidyr)
bind_rows(l) %>% 
  pivot_longer(everything()) %>% 
  full_join(df, by=c("name"="group")) %>% 
  select(name, value = value.y, value_l=value.x)
 name  value value_l
  <chr> <dbl>   <dbl>
1 A         1     999
2 B         2      55
3 C         3      NA
  • Related