YouTip LogoYouTip

R Func Substr

# Extract characters 2 to 5 result1 <-substr(text, 2, 5) print(result1) # Extract substrings from a vector words <-c("apple", "banana", "cherry") result2 <-substr(words, 1, 3) print(result2) # Replace substring str<-"Hello TUTORIAL" substr(str, 7, 12)<-"WORLD" print(str)

The output result of executing the above code is:

 "ello"
 "app" "ban" "che"
 "Hello WORLD"

substr() is often used to extract fixed-format coded information:

Example

# Extract birth year from ID number (positions 7-10)

 id_numbers <-c("110101199001011234", "310105198505067890")

 birth_years <-substr(id_numbers, 7, 10)

print(paste("Birth year:", birth_years))

The output result of executing the above code is:

 "Birth year: 1990" "Birth year: 1985"

Image 4: R Language Examples R Language Examples

← R Func SummaryR Func Strsplit β†’