[R] creating table with sequences of numbers based on the table

arun smartpink111 at yahoo.com
Thu Mar 13 16:01:00 CET 2014


Hi,
Try:
Either

tab <- read.table(text="pop Freq
1       1   30
2       2   25
3       3   30
4       4   30
5       5   30
6       6   30
7       7   30",sep="",header=TRUE)

indx <- rep(1:nrow(tab),tab$Freq)
tab1 <- transform(tab[indx,],ind=ave(seq_along(indx),indx,FUN=seq_along))[,-2]
#or
tab2 <-  transform(tab[indx,],ind=unlist(sapply(tab$Freq,seq)))[,-2]
identical(tab1,tab2)
#[1] TRUE
#or
tab3 <- transform(tab[indx,], ind= with(tab,seq_len(sum(Freq))-rep(cumsum(c(0L,Freq[-length(Freq)])),Freq)))[,-2]
identical(tab1,tab3)
#[1] TRUE

A.K.


I have a problem with transfering one table to another automatically. From table like this: 

> tab 
  pop Freq 
1       1   30 
2       2   25 
3       3   30 
4       4   30 
5       5   30 
6       6   30 
7       7   30 

I want to use number of individuals (freq) and then in next 
table just list them with following numbers (depending on total number 
of individuals) 
Like this: 
in 
pop        ind 
  
1              1 
1              2 
1              3 
1              4 
.               . 
.               . 
1              30 
2              1 
2              2 
2              3 
2              4 
.               . 
2              25 
3              1 
3              2 
.               . 
.               . 

How can i do it? I think i have to use loops but so far I failed. 
Thank you in advance, 
Best, 
Malgorzata Gazda



More information about the R-help mailing list