【问题标题】:tidyr enframe vs pivot_longer for named vectortidyr enframe vs pivot_longer 用于命名向量
【发布时间】:2019-12-07 19:04:21
【问题描述】:

对于将命名向量转换为 2 列 tibble,pivot_longer() 的工作方式似乎与 enframe() 相同,但事实并非如此。

names <- c("John", "Steve", "Jim", "Christopher")
name_chars <- sapply(names, nchar)

name_chars_enf <- enframe(name_chars, name = "Name", value = "Chars")

  # A tibble: 4 x 2
  Name        Chars
  <chr>       <int>
1 John            4
2 Steve           5
3 Jim             3
4 Christopher    11

name_chars_piv_long <- pivot_longer(name_chars, names_to = "Name", values_to = "Chars")

Error in is_call(expr, paren_sym) : 
  argument "expr" is missing, with no default

为什么pivot_longer() 不能这样工作?

【问题讨论】:

  • 如果您查看pivot_longer() 中的data 参数,它会显示A data frame to pivot
  • 我的监督。谢谢。

标签: r tidyr


【解决方案1】:

正如@tmfmnk 所述,您需要使用pivot_longer 将向量转换为数据框:

library(tidyverse)
t <- data.frame(rbind(name_chars))
t %>% pivot_longer(everything(),names_to = "Names",values_to = "Chars")

# A tibble: 4 x 2
  Names       Chars
  <chr>       <int>
1 John            4
2 Steve           5
3 Jim             3
4 Christopher    11

替代方案(由@akrun 提供)

你可以在一行中使用:

name_chars %>% as.list %>% as_tibble() %>% pivot_longer(everything())

【讨论】:

  • 谢谢。事实证明,除了 data.frame 问题之外,由于我没有将everything() 作为pivot_longer() 中的第二个参数包括在内,因此引发了错误。
  • 我在尝试重现您的示例时遇到了这个错误。这就是我发布答案的原因
  • 或使用name_chars %&gt;% as.list %&gt;% as_tibble %&gt;% pivot_longer(everything())
  • @akrun,是的,这也是可行的。谢谢。我会把它添加到我的答案中
猜你喜欢
  • 2020-10-07
  • 2021-09-07
  • 2022-01-08
  • 2021-05-28
  • 2021-12-19
  • 1970-01-01
  • 2015-07-17
  • 2020-05-24
  • 1970-01-01
相关资源
最近更新 更多