如何在 R 数据框中查找字符值的行和列索引?
要查找 R 数据框中数值的行列索引,我们可以使用 which 函数;如果该值是字符型,则使用相同的函数,但需要适当地传递该值。例如,如果我们有一个名为 df 的数据框,其中包含一个名为 Data 的值,则可以通过使用 which(df=="Data",arr.ind=TRUE) 命令来查找 Data 的行列索引。
示例1
考虑以下数据框 -
> x1<-sample(c("Male","Female"),20,replace=TRUE) > x2<-rpois(20,5) > df1<-data.frame(x1,x2) > df1
输出
x1 x2 1 Female 5 2 Female 5 3 Female 6 4 Female 6 5 Male 6 6 Female 6 7 Female 7 8 Male 0 9 Male 4 10 Male 3 11 Male 8 12 Female 6 13 Female 5 14 Male 5 15 Male 4 16 Male 7 17 Female 4 18 Male 4 19 Male 3 20 Male 5
查找 df1 中 Male 的行列索引 -
> which(df1=="Male",arr.ind=TRUE)
输出
row col [1,] 5 1 [2,] 8 1 [3,] 9 1 [4,] 10 1 [5,] 11 1 [6,] 14 1 [7,] 15 1 [8,] 16 1 [9,] 18 1 [10,] 19 1 [11,] 20 1
示例2
> y1<-sample(c("India","UK","USA"),20,replace=TRUE) > y2<-sample(c("Egypt","UK","Sudan"),20,replace=TRUE) > df2<-data.frame(y1,y2) > df2
输出
y1 y2 1 UK Sudan 2 USA Egypt 3 India UK 4 UK Egypt 5 UK Sudan 6 India UK 7 USA Egypt 8 UK UK 9 UK Sudan 10 USA Egypt 11 UK Egypt 12 India Egypt 13 India Egypt 14 India Egypt 15 UK UK 16 India Sudan 17 UK Sudan 18 UK UK 19 UK Sudan 20 India Sudan
查找 df2 中 UK 的行列索引 -
> which(df2=="UK",arr.ind=TRUE)
输出
row col [1,] 1 1 [2,] 4 1 [3,] 5 1 [4,] 8 1 [5,] 9 1 [6,] 11 1 [7,] 15 1 [8,] 17 1 [9,] 18 1 [10,] 19 1 [11,] 3 2 [12,] 6 2 [13,] 8 2 [14,] 15 2 [15,] 18 2
示例3
> z1<-sample(c("Milk","Curd","Pastry"),20,replace=TRUE) > z2<-sample(c("Milk","Tea"),20,replace=TRUE) > df3<-data.frame(z1,z2) > df3
输出
z1 z2 1 Pastry Tea 2 Pastry Milk 3 Milk Milk 4 Pastry Tea 5 Curd Tea 6 Pastry Tea 7 Curd Tea 8 Curd Tea 9 Milk Tea 10 Milk Tea 11 Pastry Milk 12 Pastry Tea 13 Curd Milk 14 Milk Tea 15 Milk Milk 16 Curd Tea 17 Milk Tea 18 Curd Tea 19 Curd Milk 20 Milk Milk
查找 df3 中 Milk 的行列索引 -
> which(df3=="Milk",arr.ind=TRUE)
输出
row col [1,] 3 1 [2,] 9 1 [3,] 10 1 [4,] 14 1 [5,] 15 1 [6,] 17 1 [7,] 20 1 [8,] 2 2 [9,] 3 2 [10,] 11 2 [11,] 13 2 [12,] 15 2 [13,] 19 2 [14,] 20 2
广告