从 R 中的 S4 class 输出中检索值
Retrieve a value from S4 class output in R
我正在用 R 编写模拟。我决定在我的函数中使用 S4 class 到 return 两个值。当我 运行 模拟时,我想知道如何从输出中检索值以计算它们的分布矩,例如均值?
setClass(Class="Coalescent",
representation(
TMRCA="numeric",
t_total="numeric"
)
)
输出如下所示:
> TMRCA_sim <-replicate(10000, Coalescent_fun(n, Ne))
> head(TMRCA_sim)
[[1]]
An object of class "Coalescent"
Slot "TMRCA":
[1] 6.723592
Slot "t_total":
[1] 9.693661
[[2]]
An object of class "Coalescent"
Slot "TMRCA":
[1] 1.592346
Slot "t_total":
[1] 11.50406
我想做的是提取 "TMRCA" 和 "t_total" 的所有值并计算平均值。当然,我可以使用许多其他方法来进行模拟,但我想同时学习 classes 的使用。
您可以将数据提取到矩阵中:
mx <- sapply(TMRCA_sim, function(x) sapply(slotNames(x), slot, object=x))
有了一些虚构的数据,这就是 mx
的样子:
[,1] [,2] [,3] [,4] [,5]
TMRCA 0.3823880 0.3403490 0.5995658 0.1862176 0.6684667
t_total 0.8696908 0.4820801 0.4935413 0.8273733 0.7942399
然后你可以使用rowMeans
或apply
:
rowMeans(mx)
apply(mx, 1, mean) # equivalent, though slower and more flexible
apply(mx, 1, var)
尽管正如我在评论中指出的那样,这是在 R 中做事的一种非常缓慢的方式。您希望 Coalescent_fun
生成具有两个向量的对象,每个向量都有许多条目,而不是每次模拟一个对象。
我正在用 R 编写模拟。我决定在我的函数中使用 S4 class 到 return 两个值。当我 运行 模拟时,我想知道如何从输出中检索值以计算它们的分布矩,例如均值?
setClass(Class="Coalescent",
representation(
TMRCA="numeric",
t_total="numeric"
)
)
输出如下所示:
> TMRCA_sim <-replicate(10000, Coalescent_fun(n, Ne))
> head(TMRCA_sim)
[[1]]
An object of class "Coalescent"
Slot "TMRCA":
[1] 6.723592
Slot "t_total":
[1] 9.693661
[[2]]
An object of class "Coalescent"
Slot "TMRCA":
[1] 1.592346
Slot "t_total":
[1] 11.50406
我想做的是提取 "TMRCA" 和 "t_total" 的所有值并计算平均值。当然,我可以使用许多其他方法来进行模拟,但我想同时学习 classes 的使用。
您可以将数据提取到矩阵中:
mx <- sapply(TMRCA_sim, function(x) sapply(slotNames(x), slot, object=x))
有了一些虚构的数据,这就是 mx
的样子:
[,1] [,2] [,3] [,4] [,5]
TMRCA 0.3823880 0.3403490 0.5995658 0.1862176 0.6684667
t_total 0.8696908 0.4820801 0.4935413 0.8273733 0.7942399
然后你可以使用rowMeans
或apply
:
rowMeans(mx)
apply(mx, 1, mean) # equivalent, though slower and more flexible
apply(mx, 1, var)
尽管正如我在评论中指出的那样,这是在 R 中做事的一种非常缓慢的方式。您希望 Coalescent_fun
生成具有两个向量的对象,每个向量都有许多条目,而不是每次模拟一个对象。