Home > OS >  How to refer to specific row in R by row name?
How to refer to specific row in R by row name?

Time:12-26

I have just loaded built-in R data set 'emissions'. I would like to remove from data set first row 'United States'. Apparently I can do it like: data2 <- data[1,] but what, if i know the name of row but not a position in data set? How to remove it refering only to name, knowing that this row is named 'United States'? Here is how data set looks like:

      GDP perCapita  CO2
UnitedStates  8083000     29647 6750
Japan         3080000     24409 1320
Germany       1740000     21197 1740
France        1320000     22381  550
UnitedKingdom 1242000     21010  675
Italy         1240000     21856  540
Russia         692000      4727 2000
Canada         658000     21221  700
Spain          642400     16401  370
Australia      394000     20976  480
Netherlands    343900     21755  240
Poland         280700      7270  400
Belgium        236300     23208  145
Sweden         176200     19773   75

I only tried to refer to it by row positions. Works fine, but I guess in bigger data sets I will not scroll trough rows and count them...

CodePudding user response:

You could filter your dataframe by row.names using the following code:

data2[!(row.names(data2) %in% "UnitedStates"),]
#>                   GDP perCapita  CO2
#> Japan         3080000     24409 1320
#> Germany       1740000     21197 1740
#> France        1320000     22381  550
#> UnitedKingdom 1242000     21010  675
#> Italy         1240000     21856  540
#> Russia         692000      4727 2000
#> Canada         658000     21221  700
#> Spain          642400     16401  370
#> Australia      394000     20976  480
#> Netherlands    343900     21755  240
#> Poland         280700      7270  400
#> Belgium        236300     23208  145
#> Sweden         176200     19773   75

Created on 2022-12-26 with reprex v2.0.2

Make sure you spelled the row name right.


Data:

data2 <- read.table(text = '      GDP perCapita  CO2
UnitedStates  8083000     29647 6750
Japan         3080000     24409 1320
Germany       1740000     21197 1740
France        1320000     22381  550
UnitedKingdom 1242000     21010  675
Italy         1240000     21856  540
Russia         692000      4727 2000
Canada         658000     21221  700
Spain          642400     16401  370
Australia      394000     20976  480
Netherlands    343900     21755  240
Poland         280700      7270  400
Belgium        236300     23208  145
Sweden         176200     19773   75', header = TRUE)

CodePudding user response:

yet another approach:

setdiff(rownames(data2), 
        c('UnitedStates', 'SkipThis', 'OmitThatToo')
        ) %>% 
  data2[., ]
  •  Tags:  
  • r
  • Related