假设我在 R 中有一个列表或数据框,我想获取行索引,我该怎么做?也就是说,我想知道某个矩阵由多少行组成。
7 回答
我将您的问题解释为关于获取行号。
as.numeric(rownames(df))
如果您没有设置行名,您可以尝试。否则使用1:nrow(df)
.- 该
which()
函数将 TRUE/FALSE 行索引转换为行号。
目前还不清楚您到底要做什么。
要引用数据框中的一行,请使用df[row,]
要获得某个向量中的第一个位置,请使用match(item,vector)
,其中向量可以是数据框的列之一,例如,df$cname
如果列名是 cname。
编辑:
要结合这些,您将编写:
df[match(item,df$cname),]
请注意,匹配项会为您提供列表中的第一项,因此如果您不是在寻找唯一的参考编号,您可能需要考虑其他内容。
见row
中?base::row
。这给出了任何类似矩阵的对象的行索引。
rownames(dataframe)
这将为您提供数据框的索引
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.
也许这个“匹配”的补充示例会有所帮助。
有两个数据集:
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
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")))