Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To rename values in R that need to be truncated at various positions, you can use the substring() function.

Syntax:

substring(x, first, last)
  • x is the vector or column that you want to modify.
  • first is the position of the first character to include in the new name.
  • last is the position of the last character to include in the new name.

Example:

Consider a data frame with a column named Name that has values you want to truncate, like below:

df <- data.frame(Name = c("John Smith", "Jane Doe", "William Johnson", "Emma Stone"))

To keep only the first 5 characters of each name, you can use the substring() function like this:

df$Name <- substring(df$Name, 1, 5)

This will modify the Name column to have the new truncated names:

> df
  Name
1  John 
2  Jane 
3  Willi
4  Emma