CaseebRamos
CaseebRamos

Reputation: 684

Why does substr() return an empty string?

I don't know if I have a logical error, but my substr() function is keep returning an empty string? My initial thought was that I am cutting the string wrong, however even with a lower starting value, I am getting null string in my dataframe column.

I have looked at this PHP question to get some information, but didn't work: PHP: substr returns empty string

Reproducible example-

#Original Data set str() output
#'data.frame':  9245 obs. of  3 variables:
#$ Latitude   : num  29.7 29.7 29.7 29.6 29.7 ...
#$ Longitude  : num  -82.3 -82.4 -82.3 -82.4 -82.3 ...
#$ Census Code: chr  "120010011003032" "120010010004035" "120010002003009" "120010015213000" ...

#For example, even if I do this:
base::substr("120010011003032", 6, 1)

#Output : ""
#Desired output: 001100

I needed to cut census codes to generate tract information, and the tract information is usually first two being the state, next three the county, and the following six the tract.

Upvotes: 0

Views: 1795

Answers (2)

smci
smci

Reputation: 33938

You need base::substr("120010011003032", 1, 6) ! (EDIT: or 11, 6 per your comment)

The arguments are start, stop not length, start; see the doc or type ?base::substr. Tip: always triple-check the R doc first. And also try copy-pasting the working examples it gives you, then see if/how they differ from yours. Or just try various argument values.

Upvotes: 2

Eugene Chong
Eugene Chong

Reputation: 1741

base::substr("120010011003032", 6, 11)

"001100"

Upvotes: 1

Related Questions