0

I have a large data set and would like to find the row where multiple columns equal a specific value.

@Dij helped point me towards 'which' but unfortunately if I look for a row beyond row 9 of the data table, I receive an 'integer(0)' error

#Example##
Constants <- data.frame(Functional_Class_Code=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19),
F_Code=c(1,3,0,0,0,4,5,6,7,0,1,2,0,3,0,4,5,6,7),
Urban_Rural=c("R","R","0","0","0","R","R","R","R","0","U ","U ","0","U ","0","U ","U ","U ","U "),
g=c(0.0127,0.0202,0,0,0,0.0153,0.0156,0.0161,0.0185,0,0.0087,0.0129,0,0.0118,0,0.0112,0.0154,0.0154,0.0229))

##Example 1: find row 8 with the following DOES work...
UR = "R"
FC = 6
TheRow = which(Constants$Urban_Rural == UR & Constants$F_Code == FC)
TheRow

##Example 2: find row 14 with the following does NOT work...
UR = "U"
FC = 3
TheRow = which(Constants$Urban_Rural == UR & Constants$F_Code == FC)
TheRow
##error returned: integer(0)

Example 1 returns 8 correctly Example 2 should return 14 but does not

chinsoon12
  • 25,005
  • 4
  • 25
  • 35
EricW
  • 69
  • 5
  • 2
    the reason is you do not have "U" but "U " in the column `Urban_Rural`. If you try with `UR="U "` then this should work – fmarm Aug 15 '19 at 00:29
  • Great catch on that - completely an error when I transformed the data. Thanks! – EricW Aug 15 '19 at 02:42

1 Answers1

0

As rightly pointed out by @fmarm while creating the dataframe, you have created Urban_Rural column with "U " (note the space) and not "U" which you are comparing with. "U " != "U"

You could remove the whitespace by using trimws on Urban_Rural column.

Constants$Urban_Rural <- trimws(Constants$Urban_Rural)

and then check

UR = "U"
FC = 3

which(Constants$Urban_Rural == UR & Constants$F_Code == FC)
#[1] 14
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    This is why I love this community. Thanks so much for pointing out my silly user error! – EricW Aug 15 '19 at 02:46