[R] R for loop stops after 4 iterations

Duncan Murdoch murdoch.duncan at gmail.com
Sun Oct 23 02:31:52 CEST 2011


On 11-10-22 7:33 PM, Philip Robinson wrote:
> I have a data frame called e, dim is 27,3, the first 5 lines look like this:
>
>
>
>
>
>       V1   V2   V3        V4
>
> 1  1673 0.36 0.08  Smith
>
> 2   167 0.36 0.08     Allen
>
> 3    99 0.37 0.06     Allen
>
> 4   116 0.38 0.07     Allen
>
> 5    95 0.41 0.08     Allen
>

That doesn't look like 3 columns, it looks like 4.

>
>
> I am trying to calculate the proportion/percentage of V1 which would have
> values>0.42 if V2 was the mean of a normal distribution with V1 people and
> a standard distribution of V3. The loop works but only for 4 iterations then
> stops, I can't understand why, the code and the output are below
>
>
>
>
>
> output<- rep(NA, 27)
>
> for (i in 1:length(e))

The length of a dataframe is the number of columns.  Use nrow(e) for the 
number of rows.

Duncan Murdoch

>
> {
>
> x<- rnorm(n=e[i,1], mean=e[i,2], sd=e[i,3])
>
> n<- e[i,1]
>
> v<- x>0.42
>
> q<-(sum(v)/n)*100
>
> output[i]<- q
>
> }
>
>
>
>> output
>
> [1] 22.23551 27.54491 25.25253 19.82759       NA       NA       NA       NA
> NA
>
> [10]       NA       NA       NA       NA       NA       NA       NA       NA
> NA
>
> [19]       NA       NA       NA       NA       NA       NA       NA       NA
> NA
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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