To convert a Character (string) column to an Integer column in R DataFrame:
df$column_name <- as.integer(df$column_name)
Example of Converting Character to Integer Column in R DataFrame
In the following example, the character ‘Price‘ column is converted to integer column in R DataFrame:
# Create a DataFrame df <- data.frame( Product = c("Laptop", "Printer", "Keyboard"), Price = c("950", "250", "120") ) # Display the original DataFrame print("Original DataFrame:") print(df) # Print the data types before conversion print("Data Types Before Conversion:") str(df) # Convert the Price column to integer df$Price <- as.integer(df$Price) # Print the data types after conversion print("Data Types After Conversion:") str(df)
Note that the str(df) was added to print the data types of the columns before and after the conversion.
The result before and after the conversion of the ‘Price‘ column from character to integer:
[1] "Original DataFrame:"
Product Price
1 Laptop 950
2 Printer 250
3 Keyboard 120
[1] "Data Types Before Conversion:"
'data.frame': 3 obs. of 2 variables:
$ Product: chr "Laptop" "Printer" "Keyboard"
$ Price : chr "950" "250" "120"
[1] "Data Types After Conversion:"
'data.frame': 3 obs. of 2 variables:
$ Product: chr "Laptop" "Printer" "Keyboard"
$ Price : int 950 250 120
As seen in the original DataFrame, the ‘Price‘ column had a character data type (as highlighted in yellow), but changed to integer (as highlighted in green).