根据列值、R、多个条件获取行名称

nx7onnlm  于 2023-03-05  发布在  其他
关注(0)|答案(3)|浏览(109)

使用示例数据集mtcars

head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

我想在cyl==4的所有情况下将行名称放入向量中|气缸==6
我找到密码了

rowname_vec<-which(mtcars[mtcars$cyl==4,])

但是我不知道如何在多个条件下使用它。(获取4a6cyl汽车的行名称)

js4nwp54

js4nwp541#

使用%in%

row.names(mtcars)[with(mtcars, cyl %in% c(4, 6))]
olhwl3o2

olhwl3o22#

使用|运算符可以过滤多个cyl值:

rowname_vec <- rownames(mtcars[mtcars$cyl==4 | mtcars$cyl==6,])

rowname_vec

 [1] "Mazda RX4"      "Mazda RX4 Wag"  "Datsun 710"     "Hornet 4 Drive" "Valiant"        "Merc 240D"      "Merc 230"       "Merc 280"       "Merc 280C"     
[10] "Fiat 128"       "Honda Civic"    "Toyota Corolla" "Toyota Corona"  "Fiat X1-9"      "Porsche 914-2"  "Lotus Europa"   "Ferrari Dino"   "Volvo 142E"

或使用tidyverse系列的filter()

library(tidyverse)
rowname_vec <- rownames(filter(mtcars, cyl == 4  | cyl == 6))
rowname_vec

     [1] "Mazda RX4"      "Mazda RX4 Wag"  "Datsun 710"     "Hornet 4 Drive" "Valiant"        "Merc 240D"      "Merc 230"       "Merc 280"       "Merc 280C"     
    [10] "Fiat 128"       "Honda Civic"    "Toyota Corolla" "Toyota Corona"  "Fiat X1-9"      "Porsche 914-2"  "Lotus Europa"   "Ferrari Dino"   "Volvo 142E"
iibxawm4

iibxawm43#

使用subset + row.names的基本选项

> row.names(subset(mtcars, abs(cyl - 5) == 1))
 [1] "Mazda RX4"      "Mazda RX4 Wag"  "Datsun 710"     "Hornet 4 Drive"
 [5] "Valiant"        "Merc 240D"      "Merc 230"       "Merc 280"
 [9] "Merc 280C"      "Fiat 128"       "Honda Civic"    "Toyota Corolla"
[13] "Toyota Corona"  "Fiat X1-9"      "Porsche 914-2"  "Lotus Europa"
[17] "Ferrari Dino"   "Volvo 142E"

相关问题