如何使用R为数据集中的不同组拟合函数

如何使用R为数据集中的不同组拟合函数,r,R,请问,如何使用R为数据集中的不同组拟合函数。第一列是组,即图,第二列是观察变量,即深度 Plot Depth 1 12.5 1 14.5 1 15.8 1 16.1 1 18.9 1 21.2 1 23.4 1 25.7 2 13.1 2 15.0 2 15.8 2 16.3 2 17.4 2 18.6 2 22.6 2 24.1 2 25.6 3 11.5 3 12.2 3 13.9 3 14.7 3 18.9 3 20.5 3 21.6 3 22.6 3 24.1 3 25.8 4 10.2

请问,如何使用R为数据集中的不同组拟合函数。第一列是组,即图,第二列是观察变量,即深度

Plot Depth
1 12.5
1 14.5
1 15.8
1 16.1
1 18.9
1 21.2
1 23.4
1 25.7
2 13.1
2 15.0
2 15.8
2 16.3
2 17.4
2 18.6
2 22.6
2 24.1
2 25.6
3 11.5
3 12.2
3 13.9
3 14.7
3 18.9
3 20.5
3 21.6
3 22.6
3 24.1
3 25.8
4 10.2
4 21.5
4 15.1
4 12.3
4 10.0
4 13.5
4 16.5
4 19.2
4 17.6
4 14.1
4 19.7
我使用了'for'语句,但只看到了Plot 1的输出。 这就是我应用“for”语句的方式:

在R中导入数据后,我将其保存为:SNq

for (i in 1:SNq$Plot[i]) {
    dp <- SNq$Depth[SNq$Plot==SNq$Plot[i]]
    fit1 = fitdist(dp, "gamma") ## this is the function I'm fitting. The function is not the issue. My challenge is the 'for' statement.
    fit1
}

我认为这应该行得通。只需对代码进行一次更改:

为什么它会起作用

因为:unique函数将返回唯一值1、2、3,这些值只不过是Plot列中的组。使用唯一值,我们可以使用SNq$Depth[SNq$Plot==i]对数据进行子集划分,并获得该组的深度值

for (i in unique(SNq$Plot)) { # <- here
    dp <- SNq$Depth[SNq$Plot==i]
    fit1 = fitdist(dp, "gamma") ## this is the function I'm fitting. The function is not the issue. My challenge is the 'for' statement.
    plot(fit1)
}
尝试:

整洁的建议:

library("tidyverse")
library("fitdistrplus")

fits <- SNq %>%
  group_by(Plot) %>%
  nest() %>%
  mutate(fits = map(data, ~ fitdist(data = .$Depth, distr = "gamma")),
         summaries = map(fit, summary))

您可以继续使用printfits$fits和printfits$summaries来访问不同的fits及其摘要。或者,您可以使用fits$fits[[1]]和fits$summaries[[1]]等语法来访问它们

我认为您在第1行SNq$Plot]中有一个错误,括号将导致错误。你能用一句话解释一下区别是什么吗。或者你为什么要改变?对不起,我的错!现在更正了。让我也解释一下,同样的结果。图1修改的唯一结果无效。为第一个情节带来了结果。很抱歉听到这个消息。您可以尝试在map函数中使用~fitdistdata=Depth,distr=gamma或~fitdistdata=.$Depth,distr=gamma。我知道这段代码。但是有没有办法一次为所有绘图运行这样的函数呢?我的答案中的mutate函数一次为所有绘图运行fitdist函数,从而生成适合每个绘图的模型。我已经更新了我的原始答案,并做了一些澄清,超级美味,请将结果强制到dataframe中。假设通过绘图将参数估计强制转换为数据帧
library("tidyverse")
library("fitdistrplus")

fits <- SNq %>%
  group_by(Plot) %>%
  nest() %>%
  mutate(fits = map(data, ~ fitdist(data = .$Depth, distr = "gamma")),
         summaries = map(fit, summary))