Suppose I have a list or data frame in R, and I would like to get the row index, how do I do that?
A:
It not quite clear what exactly you are trying to do.
To reference a row in a data frame use df[row,]
To get the first position in a vector of something use match(item,vector)
, where the vector could be one of the columns of your data frame, eg df$cname
if the column name is cname.
Edit:
To combine these you would write:
df[match(item,df$cname),]
Note that the match gives you the first item in the list, so if you are not looking for a unique reference number, you may want to consider something else.
James
2010-03-03 11:11:49
+1 Ironically, this is the best answer. :)
Shane
2010-03-03 14:08:47
A:
I'm interpreting your question to be about getting row numbers.
- You can try as.numeric(rownames(df)) if you haven't set the rownames. Otherwise use a sequence of 1:nrow(df).
- The which() function converts a true/false row index into row numbers.
Shane
2010-03-03 11:34:00
A:
If i understand your question, you just want to be able to access items in a data frame (or list) by row:
x = matrix( ceiling(9*runif(20)), nrow=5 )
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x) # create a small data frame
df[1,] # get the first row
df[3,] # get the third row
df[nrow(df),] # get the last row
lf = as.list(df)
lf[[1]] # get first row
lf[[3]] # get third row
etc.
doug
2010-03-03 11:59:09