unnest_longer函数用于展开包含字符和列表条目的列。

huangapple go评论60阅读模式
英文:

unnest_longer column with char and list entries

问题

I am trying to convert JSON file to tibble. First I combine all list entries of the JSON file to a tibble that looks like this:

df <- tibble(none_nested = c("a", "b", "c"), 
             all_nested = c(list(list("a", "b")), list(list("a", "b")), list(list("a", "b"))), 
             some_nested = c("a", "b", list(list("a", "b")))
             )

The problem is that I cannot call unnest_longer on some_nested.

unnest_longer(df, some_nested)

->
Error in `col_to_long()`:
! Can't combine `..1$some_nested` <character> and `..4$some_nested` <list>.
英文:

I am trying to convert JSON file to tibble. First I combine all list entries of the JSON file to a tibble that looks like this:

df &lt;- tibble(none_nested = c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;), 
             all_nested = c(list(list(&quot;a&quot;, &quot;b&quot;)), list(list(&quot;a&quot;, &quot;b&quot;)), list(list(&quot;a&quot;, &quot;b&quot;))), 
             some_nested = c(&quot;a&quot;, &quot;b&quot;, list(list(&quot;a&quot;, &quot;b&quot;)))
             )

The problem is that I cannot call unnest_longer on some_nested.

unnest_longer(df, some_nested)

-&gt; 
Error in `col_to_long()`:
! Can&#39;t combine `..1$some_nested` &lt;character&gt; and `..4$some_nested` &lt;list&gt;.

答案1

得分: 1

some_nested列中,一些行不在列表中(第一行和第二行是字符),因此您无法使用unnest_longer

下面的代码应该可以工作:

df %>%
  mutate(some_nested = map(some_nested, ~if(is.list(.x)) .x else list(.x))) %>%
  unnest_longer(some_nested)
英文:

In the some_nested column, some rows are not in the list (first and second rows are in char) so you couldn't use the unnest_longer.

below code should work

df |&gt; 
  mutate(some_nested = map(some_nested, ~if(is.list(.x)) .x else list(.x))) |&gt; 
  unnest_longer(some_nested)

huangapple
  • 本文由 发表于 2023年5月29日 20:09:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定