73

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

4

7 回答 7

95

我将您的问题解释为关于获取行号。

  • as.numeric(rownames(df))如果您没有设置行名,您可以尝试。否则使用1:nrow(df).
  • which()函数将 TRUE/FALSE 行索引转换为行号。
于 2010-03-03T11:34:00.433 回答
17

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

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

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

编辑:

要结合这些,您将编写:

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

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

于 2010-03-03T11:11:49.413 回答
12

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

于 2011-06-20T05:08:54.750 回答
7
rownames(dataframe)

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

于 2020-04-29T06:35:51.443 回答
4

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.

于 2010-03-03T11:59:09.643 回答
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"))

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

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

匹配从第二个给定名称返回 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

于 2018-11-30T13:16:02.890 回答
1
x <-  matrix(ceiling(9*runif(20)), nrow=5)
colnames(x) <-  c("these", "are", "the", "columnes")
df <-  data.frame(x)

结果: 数据框

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")))
于 2021-03-25T13:14:41.383 回答