Friends I cannot find this documented anyplace. I have a data frame with, say, 2 cols d<-data.frame(x=c(1:5), y=seq(from=2, to=10, by=2))> dx y 1 1 2 2 2 4 3 3 6 4 4 8 5 5 10 And I want to collect each row where the first col is prime. To this end I have a function is.prime() I want to say something like... q<-data.frame() qi<-1 for(i in 1:5){ if(is.prime(d[i, 1])){ q[qi,]<-d[i,] qi<-qi+1 } } but I get a "Warning in `[<-.data.frame`(`*tmp*`, qi, , value = list(x = 3L, y = 6)) : provided 2 variables to replace 0 variables " message. How can I accomplish this? cheers Worik [[alternative HTML version deleted]]
There are two issues here. The specifics of the error message are because you declared a data.frame with 0 columns and then attempted to change two columns. > data.frame() data frame with 0 columns and 0 rows > q <- data.frame() > q[1,] <- data.frame(a=3, b=6) Warning in `[<-.data.frame`(`*tmp*`, 1, , value = list(a = 3, b = 6)) : provided 2 variables to replace 0 variables > The second issue is that you need to read about logical subscripting. ?`[` Assuming your function is.prime is vectorized, meaning > is.prime(1:10) ## 2 3 5 7 [1] FALSE TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE FALSE then this single statement will do what you want qq <- d[is.prime(d[,1]),] I recommend you not use "q" as a variable name. It will cause you trouble later when you confuse it with q() for quitting an R session. Rich