2014-05-19 1 views
0

나는 predictions라는 벡터를 만들고, 벡터는 sapply 루프 함수에 새로운 값을 추가해야합니다.Spply 함수 요소의 R을 벡터에 더할 수 없습니다

그러나 루프가 끝나면 예측 벡터는 여전히 비어 있습니다.
그런 다음 테스트를 위해 predictions <- c(predictions, 1)을 명령 줄에서 시도했는데 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) 
    }) 
+0

우리는 당신의 객체가'test.coords','pred' 및'models'이 아니므로 여러분의 코드를 테스트 할 수 없습니다. 이 게시물을 참조하십시오 http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. 제 생각에 당신의 객체'one.pre'은'NULL'입니다 (즉, "void"). – Pop

+0

@Pop one.pre의 값을 인쇄 할 수 있으므로 값이 NULL이 아닌 것이 확실합니다. – Jusleong

+0

'one.pred'의 클래스는 무엇입니까? R – Pop

답변

1

을 다음보십시오 :

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]]) 
}) 

을 코드가 예상대로 작동합니다. 적용에 의해 반환 된 벡터의 길이는 무엇이든간에. 때문입니다 :

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

을하지만, 이러한 솔루션은 2 단점이있다 : 그렇지 않으면

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

, 당신은 사용할 수 있습니다.

  1. 동적으로 "확장"당신은 변수 범위 (단지의하자와 장난하고
  2. (사실 새롭게 복사의 이전 내용 벡터를 realocates 시간이 걸리는 연산) 결과 벡터의 크기 그게 "우아하지 않다")
+0

입니다. 멋집니다! 감사! – Jusleong

+0

btw, <<< – Jusleong

+0

의 의미는 이전에 보지 못했습니다. 죄송합니다. R이 처음입니다. – Jusleong

1

이 작동합니다 :

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 
}) 
관련 문제