簡體   English   中英

sapply函數元素中的R不能添加到vector中

[英]R in sapply function element cannot be added into vector

我創建了一個名為predictions的向量,並且該向量應該在sapply循環函數中添加新值。

但是,當循環結束時,預測向量仍為空。
然后我在命令行中嘗試了predictions <- c(predictions, 1)進行測試,並將find 1成功添加到預測中。

它使我感到困惑,我錯過了一些讓它起作用的東西嗎?

    # create an empty vector
    predictions <- c()
    # loop
    sapply(1:rows.test.coords, function(i){
      each.test.row <- test.coords[i,]
      speciesName <- each.test.row[3]
      location <- c(each.test.row[1], each.test.row[2])
      row.matrix <- matrix(as.matrix(as.numeric(location)),ncol=2)
      # Get numeric value one.pre and going to add into predictions vector
      one.pre <- apply(row.matrix,1,pred,models[[speciesName]])
      # Add element into vector
      predictions <- c(predictions, one.pre)
    })

這應該工作:

 predictions <- c()
# loop
for (i in 1:rows.test.coords){
  each.test.row <- test.coords[i,]
  speciesName <- each.test.row[3]
  location <- c(each.test.row[1], each.test.row[2])
  row.matrix <- matrix(as.matrix(as.numeric(location)),ncol=2)
  # Get numeric value one.pre and going to add into predictions vector
  one.pre <- apply(row.matrix,1,pred,models[[speciesName]])
  # Add element into vector
  predictions <- c(predictions, one.pre)
}

如果你想保留sapply結構,你應該使用它:

 predictions <- sapply(1:5, function(i){
  each.test.row <- test.coords[i,]
  speciesName <- each.test.row[3]
  location <- c(each.test.row[1], each.test.row[2])
  row.matrix <- matrix(as.matrix(as.numeric(location)),ncol=2)
  # Get numeric value one.pre and going to add into predictions vector
  one.pre <- apply(row.matrix,1,pred,models[[speciesName]])
  # Add element into vector
  one.pre
})

請嘗試以下方法:

predictions <- unlist(lapply(1:rows.test.coords, function(i){
  each.test.row <- test.coords[i,]
  speciesName <- each.test.row[3]
  location <- c(each.test.row[1], each.test.row[2])
  row.matrix <- matrix(as.matrix(as.numeric(location)),ncol=2)
  # Get numeric value one.pre and going to add into predictions vector
  # return value:
  apply(row.matrix,1,pred,models[[speciesName]])
})

代碼將按預期工作,無論apply返回的向量的長度是多少。 這是因為:

unlist(lapply(1:4, function(i) 1:i))
## [1] 1 1 2 1 2 3 1 2 3 4

否則,您可以使用:

## ...
predictions <<- c(predictions, one.pre)
## ...

但是這種解決方案有兩個缺點。

  1. 你動態地“擴展”結果向量的大小(一個耗時的操作,實際上重新定位了向量並復制了它的舊內容)
  2. 你搞亂了變量范圍(讓我們說這是“不優雅的”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM