折叠列表列元素到字符串
我想将一个子类别折叠成一个逗号的字符串以进行显示。
这就是我所拥有的。
library(tibble)
eats <- tribble(
~food,~variety,
"fruit","cherry",
"fruit","apple",
"fruit","peach",
"nut","cashew",
"nut","almonds"
)
eats
#> # A tibble: 5 x 2
#> food variety
#> <chr> <chr>
#> 1 fruit cherry
#> 2 fruit apple
#> 3 fruit peach
#> 4 nut cashew
#> 5 nut almonds
这就是我想要的:
eats2 <- tribble(
~food,~varieties,
"fruit","cherry, apple, peach",
"nut","cashew, almond"
)
eats2
#> # A tibble: 2 x 2
#> food varieties
#> <chr> <chr>
#> 1 fruit cherry, apple, peach
#> 2 nut cashew, almond
我尝试的是:
eats %>%
nest(data=variety) %>%
mutate(data = paste(data,collapse = ""))
#> # A tibble: 2 x 2
#> food data
#> <chr> <chr>
#> 1 fruit "list(variety = c(\"cherry\", \"apple\", \"peach\"))list(variety = c(\"~
#> 2 nut "list(variety = c(\"cherry\", \"apple\", \"peach\"))list(variety = c(\"~
不。
eats %>%
nest(data=variety) %>%
map(~.x %>% mutate(varieties=paste(data,collapse = "")))
#> Error in UseMethod("mutate"): no applicable method for 'mutate' applied to an object of class "character"
由Reprex软件包(v2.0.1)在2022-07-01创建
。正确的方法是什么?谢谢。
I would like to collapse a subcategory into a comma-delimited string for display.
This is what I have.
library(tibble)
eats <- tribble(
~food,~variety,
"fruit","cherry",
"fruit","apple",
"fruit","peach",
"nut","cashew",
"nut","almonds"
)
eats
#> # A tibble: 5 x 2
#> food variety
#> <chr> <chr>
#> 1 fruit cherry
#> 2 fruit apple
#> 3 fruit peach
#> 4 nut cashew
#> 5 nut almonds
This is what I want:
eats2 <- tribble(
~food,~varieties,
"fruit","cherry, apple, peach",
"nut","cashew, almond"
)
eats2
#> # A tibble: 2 x 2
#> food varieties
#> <chr> <chr>
#> 1 fruit cherry, apple, peach
#> 2 nut cashew, almond
This what I've tried:
eats %>%
nest(data=variety) %>%
mutate(data = paste(data,collapse = ""))
#> # A tibble: 2 x 2
#> food data
#> <chr> <chr>
#> 1 fruit "list(variety = c(\"cherry\", \"apple\", \"peach\"))list(variety = c(\"~
#> 2 nut "list(variety = c(\"cherry\", \"apple\", \"peach\"))list(variety = c(\"~
Nope.
eats %>%
nest(data=variety) %>%
map(~.x %>% mutate(varieties=paste(data,collapse = "")))
#> Error in UseMethod("mutate"): no applicable method for 'mutate' applied to an object of class "character"
Created on 2022-07-01 by the reprex package (v2.0.1)
Also nope. What is the right way to do this? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
总结
和toString
:在2022-07-01创建的 reprex软件包(v2.0.1)
You can use the following code using
summarise
andtoString
:Created on 2022-07-01 by the reprex package (v2.0.1)
就像 @quinten的解决方案一样,只需使用
粘贴
而不是toString
:Like @Quinten's solution, just using
paste
instead oftoString
: