Skip to content
Prev 171670 / 398503 Next

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

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