2

Using the sample data set 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

I want to get the rownames into a vection in all cases where the cyl==4|cyl==6

I found the code

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

But I do not know how to make this work with multiple conditions. (getting the row names for 4 a 6 cyl cars)

aynber
  • 22,380
  • 8
  • 50
  • 63
M3Lba
  • 97
  • 7

3 Answers3

4

Using | operator you could filter for multiple cyl values:

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"

Or using filter() from tidyverse family:

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"
S-SHAAF
  • 1,863
  • 2
  • 5
  • 14
4

Using %in%

row.names(mtcars)[with(mtcars, cyl %in% c(4, 6))]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Accepted this answer vs the one below because the result gives me a vector of rownames that I can then use to subset the data the same way, regardless of if the number of rows of the data frame changes (ie, updates to the raw data) – M3Lba Mar 02 '23 at 19:16
  • both row.names() and rownames() can be used to achieve the same result of extracting the row names of a data frame as a vector and using that vector to subset the data frame. The choice between the two functions is just comes down to personal preference. – S-SHAAF Mar 02 '23 at 19:52
0

A base option using 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"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81