Skip to content
Prev 387906 / 398502 Next

Help understanding loop behaviour

Hi email,
If you want what you described, try this:

xx<-read.table(text="COMPANY_NUMBER NUMBER_OF_YEARS
0070837  3
0070837  3
0070837  3
1000403  4
1000403  4
1000403  4
1000403  4
10029943  3
10029943  3
10029943  3
10037980  4
10037980  4
10037980  4
10037980  4
10057418  3
10057418  3
10057418  3
1009550  4
1009550  4
1009550  4
1009550  4",
header=TRUE,stringsAsFactors=FALSE)
xx$I<-NA
xx$J<-NA
row_count<-1
for(row in 1:nrow(xx)) {
 if(row == nrow(xx) || xx$COMPANY_NUMBER[row]==xx$COMPANY_NUMBER[row+1]) {
  xx$I[row]<-1
  xx$J[row]<-row_count
  row_count<-row_count+1
 } else {
  xx$I[row]<-xx$J[row]<-xx$NUMBER_OF_YEARS[row]
  row_count<-1
 }
}
xx

Like Petr, I am assuming that you want company 10057418 treated the
same as the others. If not, let us know why. I am also adssuming that
the first three rows should _not_ have a "#" at the beginning, which
means that they will be discarded.

Jim

On Fri, Apr 30, 2021 at 1:41 AM e-mail ma015k3113 via R-help
<r-help at r-project.org> wrote: