Vinod P
Vinod P

Reputation: 99

Pasting list in different ways

Below code is returning a tibble as expected that is fine

Method1

df <- tibble(ID = 1:2,
             ColB = list(list(ved = "19", ved_name = "No", vedd = "11") ,
                         list(ved = c("65", "83", "2"), ved_name = c("At", "Re", "Rum"),
                              vedd = c("11", "11", "11"))))

Below is the output

df
# A tibble: 2 x 2
     ID ColB            
  <int> <list>          
1     1 <named list [3]>
2     2 <named list [3]>

But if I try performing above in different way, I am not able to

Method2

There is a list already

List_1
[[1]]
[1] "list(list(ved = "19", ved_name = "No", vedd = "11") ,
                         list(ved = c("65", "83", "2"), ved_name = c("At", "Re", "Rum"),
                              vedd = c("11", "11", "11")))"

When I execute below code, the output is different

df <- tibble(ID = 1: 2, ColB = List_1)
df
# A tibble: 5 x 2
     ID ColB     
  <int> <list>   
1    11 <chr [1]
2    12 <chr [1]>

There is a difference. So the exepected output is getting Output of Method1 using Method2 steps.Is this possible to achieve

dput(List1)
list("list(list(ved = \"19\", ved_name = \"No\", vedd = \"11\") ,
                         list(ved = c(\"65\", \"83\", \"2\"), ved_name = c(\"At\", \"Re\", \"Rum\"),
                              vedd = c(\"11\", \"11\", \"11\")))")

Upvotes: 1

Views: 37

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389012

List1 is list of length 1 with string. To read that as list as in your first example you can use eval, parse. And if you are using it also read What specifically are the dangers of eval(parse(...))? .

df <- tibble::tibble(ID = 1:2,
                     ColB = eval(parse(text = list1[[1]])))
df
# A tibble: 2 x 2
#     ID ColB            
#  <int> <list>          
#1     1 <named list [3]>
#2     2 <named list [3]>

Upvotes: 2

Related Questions