请问,如何使用R为数据集(土壤)中的不同组拟合函数。第一列是组,即Plot,第二列是观察到的变量,即深度
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
}
答案 0 :(得分:1)
我认为这应该有效。只需对代码进行一次更改:
为什么会有效?
因为:唯一函数将返回唯一值(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)
}
答案 1 :(得分:0)
tidyverse
建议:
library("tidyverse")
library("fitdistrplus")
fits <- SNq %>%
group_by(Plot) %>%
nest() %>%
mutate(fits = map(data, ~ fitdist(data = .$Depth, distr = "gamma")),
summaries = map(fit, summary))
您可以继续使用print(fits$fits)
和print(fits$summaries)
来访问不同的拟合及其摘要。或者,您可以使用fits$fits[[1]]
和fits$summaries[[1]]
等语法来访问它们。
答案 2 :(得分:-1)
尝试:
for (i in 1:nrow(SNq)) {
dp <- SNq$Depth[SNq$Plot==SNq$Plot[i]]
fit1 = fitdist(dp, "gamma")
fit1
}