[R] Have a function like the "_n_" in R ? (Automatic count function )

David Winsemius dwinsemius at comcast.net
Wed Feb 25 15:27:10 CET 2009


The _n_ construct in SAS is most analogous to that of row names in R,  
accessible (and modifiable)  via the row.names() function:

DF <- structure(list(Month = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 3L, 3L, 3L, 3L, 3L), .Label = c("Aug", "July", "Sept"), class =  
"factor"),
     Week = 27:39, Estpassage = c(665L, 2232L, 9241L, 28464L,
     41049L, 82216L, 230411L, 358541L, 747839L, 459682L, 609567L,
     979475L, 837189L), MedFL = c(34L, 35L, 35L, 35L, 35L, 35L,
     35L, 35L, 35L, 36L, 36L, 36L, 36L)), .Names = c("Month",
"Week", "Estpassage", "MedFL"), class = "data.frame", row.names = c(NA,
-13L))

DF$counter <- row.names(DF)

 > DF
    Month Week Estpassage MedFL counter
1   July   27        665    34       1
2   July   28       2232    35       2
3   July   29       9241    35       3
4   July   30      28464    35       4
5    Aug   31      41049    35       5
6    Aug   32      82216    35       6
7    Aug   33     230411    35       7
8    Aug   34     358541    35       8
9   Sept   35     747839    35       9
10  Sept   36     459682    36      10
11  Sept   37     609567    36      11
12  Sept   38     979475    36      12
13  Sept   39     837189    36      13

Row names, however, not guaranteed to be integer, although if not  
specified at time of creation a dataframe will have its row names set  
to an ascending series of integer type. Another function that would  
provide similar utility for vectors might be seq_along().\, but in the  
case of dataframes, it may confuse the beginning R user because it  
will return a column oriented ascending sequence.

 > seq_along(DF)
[1] 1 2 3 4 5

-- 
David Winsemius



On Feb 25, 2009, at 7:25 AM, Nash wrote:

>
> Have the counter function in R ?
>
> if we use the software SAS
>
> /*** SAS Code **************************/
> data tmp(drop= i);
> retain seed x 0;
> do i = 1 to 5;
> 	call ranuni(seed,x);
> 	output;
> end;
> run;
>
> data new;
> counter=_n_;  ***** this keyword _n_ ****;
> set tmp;
> run;
>
> /*
> _n_ (Automatic variables)
> are created automatically by the DATA step or by DATA step statements.
> */
>
> /*** Output ********************************
> counter	     seed             x
> 1	584043288	         0.27197
> 2	935902963	         0.43581
> 3	301879523	         0.14057
> 4	753212598	         0.35074
> 5	1607264573	0.74844
>
> ********************************************/
>
> Have a function like the "_n_" in R ?
>
>
> --
> Nash - morrison at ibms.sinica.edu.tw
>
> ______________________________________________
> 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