Watts-College / cpp-529-fall-2021

https://watts-college.github.io/cpp-529-fall-2021/
0 stars 0 forks source link

Lab04 - substr( these.fips, 1,2 ) question: #9

Open trioptre opened 2 years ago

trioptre commented 2 years ago

@AntJam-Howell

In the following code example from Lab04, can you explain what the 1,2 and 3,5 are referencing?

state.fips <- substr( these.fips, 1, 2 ) county.fips <- substr( these.fips, 3, 5 )

Thank you, Dave

mtwelker commented 2 years ago

The numbers tell what part of the substring to return. So state.fips is the 1st through 2nd characters of these.fips. And county.fips is the 3rd through 5th characters of these.fips. Here's another example:

> substr("Arizona", 1, 2)
[1] "Ar"
> substr("Arizona", 3, 5)
[1] "izo"
trioptre commented 2 years ago

Thank you, @mtwelker - however I'm still unclear as to why "izo" would be helpful in your example. What is the purpose of splitting the word "Arizona" into "Ar" and "izo"?

mtwelker commented 2 years ago

@trioptre , that was just an example of how the function works. I could have used any word there:

> substr("elephant", 1, 2)
[1] "el"
> substr("elephant", 3, 5)
[1] "eph"

In the lab, it was pulling from the crosswalk$fipscounty field, which is a 5-digit code in which the first two digits represent the state and the last three represent the county. For example, we can look up Maricopa County, AZ and see that the fipscounty is 04013, in which "04" represents Arizona and "013" represents Maricopa County. To separate those out for our counties of interest, we use substr():

> x <- "04013"
> state <- substr(x, 1, 2)
> state
[1] "04"
> county <- substr(x, 3, 5)
> county
[1] "013"