Here are three ways to convert a float to a string in R:
- Using as.character()
- Using sprintf()
- Using toString()
Method 1: Using as.character()
The as.character() function generates a string representation of a provided argument.
float_val <- 21.19
chr <- as.character(float_val)
chr
Output
[1] "21.19"
To check the variable data type, use the typeof() function.
float_val <- 21.19
chr <- as.character(float_val)
typeof(chr)
Output
[1] "character"
Method 2: Using sprintf()
To convert without losing precision, use the “sprintf()” function.
float_val <- 21.19000
chr <- sprintf("%0.5f", float_val)
print(chr)
print(typeof(chr))
Output
[1] "21.19000"
[1] "character"
Method 3: Using toString()
The toString() function returns a single character string describing an R object. It converts an object to a character type.
float_val <- 21.19
chr <- toString(float_val)
print(chr)
print(typeof(chr))
Output
[1] "21.19"
[1] "character"
That’s it!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.