You can use the following basic syntax to convert a column with TRUE and FALSE values to a column with 1 and 0 values in R:
df$my_column integer(as.logical(df$my_column))
The following example shows how to use this syntax in practice.
Example: Convert TRUE and FALSE to 1 and 0 in R
Suppose we have the following data frame in R:
#create data frame df frame(points=c(5, 7, 8, 0, 12, 14), assists=c(0, 2, 2, 4, 4, 3), all_star=c(TRUE, TRUE, FALSE, FALSE, FALSE, TRUE)) #view data frame df points assists all_star 1 5 0 TRUE 2 7 2 TRUE 3 8 2 FALSE 4 0 4 FALSE 5 12 4 FALSE 6 14 3 TRUE
We can use the following basic syntax to convert the TRUE and FALSE values in the all_star column to 1 and 0 values:
#convert all_star column to 1s and 0s df$all_star integer(as.logical(df$all_star)) #view updated data frame df points assists all_star 1 5 0 1 2 7 2 1 3 8 2 0 4 0 4 0 5 12 4 0 6 14 3 1
Each TRUE value has been converted to 1 and each FALSE value has been converted to 0.
The other columns (points and assists) have remained unchanged.
Note that you can also use the as.logical() function to convert a column of 1 and 0 values back to TRUE and FALSE values:
#convert 1s and 0s back to TRUE and FALSE in all_star column df$all_star logical(df$all_star) #view updated data frame df points assists all_star 1 5 0 TRUE 2 7 2 TRUE 3 8 2 FALSE 4 0 4 FALSE 5 12 4 FALSE 6 14 3 TRUE
The 1 and 0 values have been converted back to TRUE and FALSE values in the all_star column.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Remove Empty Rows from Data Frame in R
How to Remove Columns with NA Values in R
How to Remove Duplicate Rows in R