gpt4 book ai didi

r - 在嵌套的小标题上应用 ntile

转载 作者:行者123 更新时间:2023-12-04 11:26:39 26 4
gpt4 key购买 nike

我正在尝试申请 ntile在一些嵌套的小标题上,但我似乎无法让它工作。

你能看出我哪里出错了吗?

data(iris)

iris %>%
group_by(Species) %>%
mutate(quintile = ntile(Petal.Length, 5)) # This works

nested_iris <- iris %>%
as_tibble() %>%
group_by(Species) %>%
nest(.key = "data") %>%
mutate(quintile = map(data, ~ntile(.x, Petal.Length, 5))) #This doesn`t work

最佳答案

放置 ntile里面mutate调用并更新“数据”以在其中创建一个新列。最小化存储结构可能会更好

library(tidyverse)
o1 <- iris %>%
as_tibble() %>%
group_by(Species) %>%
nest(.key = "data") %>%
mutate(data = map(data, ~
.x %>%
mutate(quintile = ntile(Petal.Length, 5))))
# A tibble: 3 x 2
# Species data
# <fct> <list>
#1 setosa <tibble [50 × 5]>
#2 versicolor <tibble [50 × 5]>
#3 virginica <tibble [50 × 5]>

注意:假设 OP 需要所有带有附加“五分位数”的列。

然后,我们 unnest
o1 %>%
unnest
# A tibble: 150 x 6
# Species Sepal.Length Sepal.Width Petal.Length Petal.Width quintile
# <fct> <dbl> <dbl> <dbl> <dbl> <int>
# 1 setosa 5.1 3.5 1.4 0.2 2
# 2 setosa 4.9 3 1.4 0.2 2
# 3 setosa 4.7 3.2 1.3 0.2 1
# 4 setosa 4.6 3.1 1.5 0.2 3
# 5 setosa 5 3.6 1.4 0.2 2
# 6 setosa 5.4 3.9 1.7 0.4 5
# 7 setosa 4.6 3.4 1.4 0.3 2
# 8 setosa 5 3.4 1.5 0.2 3
# 9 setosa 4.4 2.9 1.4 0.2 2
#10 setosa 4.9 3.1 1.5 0.1 3
# … with 140 more rows

关于r - 在嵌套的小标题上应用 ntile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55971458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com