如何在R数据帧中找到字符值的行索引和列索引?
为了找到R数据帧中数值的行索引和列索引,我们使用哪个函数,如果该值是字符,则将使用相同的函数,但是我们需要适当地传递该值。例如,如果我们有一个名为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中找到英国的行和列索引-
> 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