如何获得R中的行索引号?

时间:2010-03-03 10:52:43

标签: r dataframe

假设我在R中有一个列表或数据框,我想得到行索引,我该怎么做?也就是说,我想知道某个矩阵包含多少行。

7 个答案:

答案 0 :(得分:70)

我正在解释你的问题是关于获取行号。

  • 如果您尚未设置rownames,可以尝试as.numeric(rownames(df))。否则使用1:nrow(df)的序列。
  • which()函数将TRUE / FALSE行索引转换为行号。

答案 1 :(得分:13)

目前还不清楚你到底要做什么。

要引用数据框中的行,请使用df[row,]

要使用match(item,vector)获取某个向量中的第一个位置,其中向量可以是数据框的其中一列,例如df$cname如果列名为cname。

编辑:

要合并这些,你会写:

df[match(item,df$cname),]

请注意,匹配会为您提供列表中的第一项,因此,如果您不寻找唯一的参考编号,您可能需要考虑其他内容。

答案 2 :(得分:10)

请参阅row中的?base::row。这给出了任何类似矩阵的对象的行索引。

答案 3 :(得分:4)

如果我理解您的问题,您只希望能够访问数据框(或列表)中的项按行

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

答案 4 :(得分:1)

也许“匹配”的补充示例会有所帮助。

有两个数据集:

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"))

如果名称列仅包含唯一的跨集合值(跨整个集合) 那么您可以按match返回的索引值访问其他数据集中的行

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

match从第二个给定名称返回first_dataset中名称的正确行索引:5 4 2 1 此处的示例-按行索引(按给定名称值)从第一个数据集中访问角色

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

答案 5 :(得分:1)

rownames(dataframe)

这将为您提供数据帧的索引

答案 6 :(得分:1)

x <-  matrix(ceiling(9*runif(20)), nrow=5)
colnames(x) <-  c("these", "are", "the", "columnes")
df <-  data.frame(x)

结果: dataframe

which(df == "2")                       #returns rowIndexes results from the entire dataset, in this case it returns a list of 3 index numb

结果:

<块引用>

5 13 17

length(which(df == "2"))               #count numb. of rows that matches the condition of ==2

结果:

<块引用>

3

您也可以明智地执行此列,例如:

which(df$columnName == c("2", "7"))     #you do the same with strings
length(which(df$columnName == c("2", "7")))