[R] replacement has length zero

Peter Ehlers ehlers at ucalgary.ca
Sun Jul 8 19:42:19 CEST 2012


On 2012-07-08 06:57, fabiano wrote:
> Thanks Peter.
>
> We had a look at both Hab and habitat. These are integers representing
> habitat types.
>
> habitat <- read.csv("Ungulate_vegetation.csv")
> habitat <- habitat[,3]
> habitat
> [1] 3 3 4 3 3 3 4 4 3 3 3 3 3 4 2 3 2 3 2 3
>
> Hab <- cbind(seq(1,20),habitat)
> Hab
>           habitat
>   [1,]  1       3
>   [2,]  2       3
>   [3,]  3       4
>   [4,]  4       3
>   [5,]  5       3
>   [6,]  6       3
>   [7,]  7       4
>   [8,]  8       4
>   [9,]  9       3
> [10,] 10       3
> [11,] 11       3
> [12,] 12       3
> [13,] 13       3
> [14,] 14       4
> [15,] 15       2
> [16,] 16       3
> [17,] 17       2
> [18,] 18       3
> [19,] 19       2
> [20,] 20       3
>
> hab
>       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
> [1,]   NA   NA   NA   NA   NA   NA   NA
> [2,]   NA   NA   NA   NA   NA   NA   NA
>
> for(i in 1:2){ hab[i, ] <- Hab[habitat==i,1] }
>
> The idea is to assign habitat types to hab.

I don't understand how this relates to a 2-by-7 matrix,
but it's easy to see where your problem with the loop is.
Try this and see if it sheds light:

   hab[1,] <- Hab[habitat==1,1]
   #Error in hab[1, ] <- Hab[habitat == 1, 1] : replacement has length zero

   hab[2,] <- Hab[habitat==2,1]
   #Error in hab[2, ] <- Hab[habitat == 2, 1] :
   number of items to replace is not a multiple of replacement length

Now do:
   Hab[habitat==1,1]    ## how many 1s are in habitat?
   Hab[habitat==2,1]    ## how many 2s are in habitat?

I think that you may have to rethink your approach.

Peter Ehlers

>
> Thanks
>
> --
> View this message in context: http://r.789695.n4.nabble.com/replacement-has-length-zero-tp4635700p4635777.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list