Search code examples
rtextdplyr

How to add attributes in data frame as list elements using dplyr left_join and export it as desired in text file?


I have one list and one data frame as below:

name <- c("A","B","C","D","E")
n <- c("1, 2, 3, 4, 5, 6, 7, 8, 9, 10", "11, 12, 13, 14, 15", "16, 17, 18, 19, 20", "21, 22, 23, 24, 25", "26, 27, 28, 29, 30, 31, 32, 33, 34, 35")
type <- c("a", "b", "c", "d", "e")

list <- list(name=name, n=n)
df <- data.frame(name=name, type=type)

Where list and df looks like this:

> list
$name
[1] "A" "B" "C" "D" "E"

$n
[1] "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"      "11, 12, 13, 14, 15"     "16, 17, 18, 19, 20" "21, 22, 23, 24, 25" "26, 27, 28, 29, 30, 31, 32, 33, 34, 35"

> df
  name type
1    A    a
2    B    b
3    C    c
4    D    d
5    E    e

I want to merge these two objects using left_join in dplyr and store contents of df as a new list object in list which looks like this:

> list
$name
[1] "A" "B" "C" "D" "E"

$n
[1] "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"      "11, 12, 13, 14, 15"     "16, 17, 18, 19, 20" "21, 22, 23, 24, 25" "26, 27, 28, 29, 30, 31, 32, 33, 34, 35"

$type
[1] "a" "b" "c" "d" "e"

Is there anyone who know how to merge list and data frame and add the result in the list? I tired the following script but it returned an error.

> list %>% left_join(.$name, df.name, by="name")
Error in UseMethod("left_join") : 
  no applicable method for 'left_join' applied to an object of class "list"

I used to use R for more simple data manipulation but have never used it for this kind of text manipulation. Your suggestions are highly appreciated.

I prefer to use pipe function in dplyr but the solution is not limited to this package. Thank you in advance for your kind suggestions.


Solution

  • Maybe using match would be easier -

    list$target <- df$type[match(list$name, df$name)]
    list
    
    #$name
    #[1] "A" "B" "C" "D" "E"
    
    #$n
    #[1] "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"         
    #[2] "11, 12, 13, 14, 15"                    
    #[3] "16, 17, 18, 19, 20"                    
    #[4] "21, 22, 23, 24, 25"                    
    #[5] "26, 27, 28, 29, 30, 31, 32, 33, 34, 35"
    
    #$target
    #[1] "a" "b" "c" "d" "e"