How do I reference the row number of an observation? For example, if you have a data.frame
called "data" and want to create a variable data$rownumber
equal to each observation's row number, how would you do it without using a loop?
相关问题
- R - Quantstart: Testing Strategy on Multiple Equit
- Using predict with svyglm
- Reshape matrix by rows
- Extract P-Values from Dunnett Test into a Table by
- split data frame into two by column value [duplica
相关文章
- How to convert summary output to a data frame?
- How to plot smoother curves in R
- Paste all possible diagonals of an n*n matrix or d
- ess-rdired: I get this error “no ESS process is as
- How to use doMC under Windows or alternative paral
- dyLimit for limited time in Dygraphs
- Saving state of Shiny app to be restored later
- How to insert pictures into each individual bar in
Perhaps with dataframes one of the most easy and practical solution is:
data = dplyr::mutate(data, rownum=row_number())
This is probably the simplest way:
It's probably worth noting that if you want to select a row by its row index, you can do this with simple bracket notation
So I'm not really sure what this new column accomplishes.
These are present by default as
rownames
when you create adata.frame
.and you can access them via the
rownames
command.if you need them as numbers, simply coerce to numeric by adding
as.numeric
, as inas.numeric(rownames(df))
.You don't need to add them, as if you know what you are looking for (say item
df$c == 'i'
, you can use the which command:or if you don't know the column
you may access the element using
df[9, 'c']
, ordf$c[9]
.If you wanted to add them you could use
df$rownumber <- as.numeric(rownames(df))
, though this may be less robust thandf$rownumber <- 1:nrow(df)
as there are cases when you might have assigned torownames
so they will no longer be the default index numbers (the which command will continue to return index numbers even if you do assign torownames
).Simply: