返回数据框中某列中特定值的行号 [英] Return row number(s) for a particular value in a column in a dataframe

查看:106
本文介绍了返回数据框中某列中特定值的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框(df),我想知道如何返回特定值(2585)的行号在同一数据框的第四列(height_chad1)中?

I have a data frame (df) and I was wondering how to return the row number(s) for a particular value (2585) in the 4th column (height_chad1) of the same data frame?

我尝试过:

row(mydata_2$height_chad1, 2585)

我收到以下错误:

Error in factor(.Internal(row(dim(x))), labels = labs) : 
  a matrix-like object is required as argument to 'row'

是否存在等效的代码行适用于数据帧而不是矩阵类对象?

Is there an equivalent line of code that works for data frames instead of matrix-like objects?

任何帮助将不胜感激。

Any help would be appreciated.

推荐答案

使用 which(mydata_2 $ height_chad1 == 2585)

简短示例

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

马特·韦勒指出,您可以使用 length 函数。
plyr 中的 count 函数可用于返回每个唯一列值的计数。

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

这篇关于返回数据框中某列中特定值的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆