要将命名的矢量转换为2列小标题,似乎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()
不能这样工作?
答案 0 :(得分:2)
如@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())