r - How to select a value if it is given in range format? -


i have data frame 1 of columns representing age. value of age given intervals shown in table below:

head(ddd) country.of.birth age     sex    x2000 x2001 x2002 x2003 x2004 x2005 x2006 x2007 afghanistan      0-4     men       0     0     1     2     2     0     1     1 afghanistan      5-9     women     1     1     0     0     1     0     0     0 afghanistan      10-14   men       0     2     5     2     3     4     1     1 afghanistan      15-19   women     4     1     4     2     3     2     3     2 afghanistan      20-24   men       5     0     8     7     7     3     5     3 afghanistan      25-29   women     4     8     3     9     4     4     4     3 

what command should use able select age range? tried:

sum(ddd[ddd$age == "20-24", 4:11]) 

to sum of columns age in range of 20-24 (should give 38), got error:

error in fun(x[[i]], ...) :  defined on data frame numeric variables 

i assume case of trailing/leading spaces. can remove trailing/leading spaces str_trim `stringr)

ddd$age[5] <- '20-29 ' sum(ddd[ddd$age == "20-29", 4:11]) #error in fun(x[[i]], ...) :  # defined on data frame numeric variables  library(stringr) sum(ddd[str_trim(ddd$age)=='20-29', 4:11]) #[1] 38 

or use sub

 ddd$age <- sub('^\\s*|\\s*$', '', ddd$age)  sum(ddd[str_trim(ddd$age)=='20-29', 4:11])  #[1] 38 

if use grep, problem can avoided

 sum(ddd[grep('20-29', ddd$age),4:11])  #[1] 38 

Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -