How to get row index number in R?

前端 未结 6 1221
无人共我
无人共我 2021-01-31 13:46

Suppose I have a list or data frame in R, and I would like to get the row index, how do I do that? That is, I would like to know how many rows a certain matrix consists of.

6条回答
  •  心在旅途
    2021-01-31 14:05

    Perhaps this complementary example of "match" would be helpful.

    Having two datasets:

    first_dataset <- data.frame(name = c("John", "Luke", "Simon", "Gregory", "Mary"),
                                role = c("Audit", "HR", "Accountant", "Mechanic", "Engineer"))
    
    second_dataset <- data.frame(name = c("Mary", "Gregory", "Luke", "Simon"))
    

    If the name column contains only unique across collection values (across whole collection) then you can access row in other dataset by value of index returned by match

    name_mapping <- match(second_dataset$name, first_dataset$name)
    

    match returns proper row indexes of names in first_dataset from given names from second: 5 4 2 1 example here - accesing roles from first dataset by row index (by given name value)

    for(i in 1:length(name_mapping)) {
        role <- as.character(first_dataset$role[name_mapping[i]])   
        second_dataset$role[i] = role
    }
    

    ===

    second dataset with new column:
         name       role
    1    Mary   Engineer
    2 Gregory   Mechanic
    3    Luke Supervisor
    4   Simon Accountant
    

    r

提交回复
热议问题