【问题标题】:Save variables in a matrix in R将变量保存在R中的矩阵中
【发布时间】:2016-04-18 21:28:04
【问题描述】:

是否可以在R中存储变量..

我必须计算 10*324 fitdist,这个函数的每个输出都必须存储在上述大小的矩阵中?这在 R 中可能吗?

如果是这样,那我完全迷路了怎么办?

所以我试着创建一个简单的例子

norm_dist <- as.data.frame(matrix(nrow=3,ncol=3))
data(iris)
for(i in 1:3)
{
  for(j in 1:3)
  {
    print(i)
    print(j)
    if(j==1)
    {
      element = fitdist(data =iris$Petal.Width[1:50*i], distr = "norm")
      norm_dist[i,j] = element
    } 
    if(j==2)
    {
      element = fitdist(data =iris$Petal.Length[1:50*i], distr = "norm")
      norm_dist[i,j] = element
    } 
   if(j==3)
    {
      element = fitdist(data =iris$Sepal.Length[1:50*i], distr = "norm")
      norm_dist[i,j] = element
    } 
  }

}

但是我收到了这个错误

Error in `[<-.data.frame`(`*tmp*`, i, j, value = list(estimate = c(0.867771222640304,  : 
  replacement element 4 is a  matrix with 2 rows, needs 1 

我不确定我是否理解它的意思......

【问题讨论】:

  • 创建一个远小于 8000*324 的示例,并将其包含在您的问题中。
  • 我尝试创建一个简单的例子
  • data(Iris) 似乎已被添加,谢谢@J.Down :) 现在看来可以重现了..
  • 欢迎来到 SO!,马修的意思是 how to post a great reproducible example
  • 现在不是这样吗?

标签: r for-loop matrix fitdistrplus


【解决方案1】:

您可能想查看“价值”部分下的?fitdist 文档。它提到了函数的输出,它是一个包含几个组件的列表。

您想将哪些值分配给norm_dist?例如,如果你想要对数似然,你可以使用norm_dist[i,j] = element$loglik

如果要存储要存储的整个对象,则需要一个列表而不是 data.frame,例如

norm_dist_res <- list()
for(i in 1:10)
{
    for(j in 1:324)
    {
        norm_dist_res[[paste0(i,"-",j)]] <- fitdist(data=g_all_p$data[1:8000*i, j], distr="norm")
    }
}

【讨论】:

  • 我收到此错误Error in [[(*tmp*, paste0(i, "-", j), value = list(estimate = c(0.867771222640304, : replacement has 17 rækker, data has 10
  • 如何提取单个值?
  • 2-1 和 3-2 具有完全相同的输入
  • 您需要在g_all_p$data[1:8000*i, j] 中检查您的索引。我不太明白您是如何访问数据向量的。本质上,我不知道g_all_p$data 是什么。
  • g_all_p$data 是一个有 80000 行和 324 列的矩阵,每个 8000 属于一个类,这些是对一个类进行的观察,这 8000 行的每一行是提取的特征。我正在尝试将每个向量拟合到规范分布。并将该变量保存在类似矩阵的结构中。
猜你喜欢
  • 2022-10-14
  • 1970-01-01
  • 2023-03-22
  • 2023-04-05
  • 2019-09-08
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多