a bar chart is shown on a blue background

The best way to Convert TRUE and FALSE to at least one and nil in R

Posted on
banner 336x280

You’ll worth refer to unadorned syntax to transform a column with TRUE and FALSE values to a column with 1 and 0 values in R:

df$my_column <- as.integer(as.logical(df$my_column))

Refer to instance presentations learn how to worth this syntax in apply.

banner 468x60

Instance: Convert TRUE and FALSE to at least one and nil in R

Assume now we have refer to information body in R:

#manufacture information body
df <- information.body(issues=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 information body
df

  issues 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 will worth refer to unadorned syntax to transform the TRUE and FALSE values within the all_star column to 1 and 0 values:

#convert all_star column to 1s and 0s
df$all_star <- as.integer(as.logical(df$all_star))

#view up to date information body
df

  issues 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 and every TRUE price has been transformed to 1 and each and every FALSE price has been transformed to 0.

The alternative columns (issues and assists) have remained unchanged.

Observe that you’ll additionally worth the as.logical() serve as to transform a column of 1 and 0 values again to TRUE and FALSE values:

#convert 1s and 0s again to TRUE and FALSE in all_star column
df$all_star <- as.logical(df$all_star)

#view up to date information body
df

  issues 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 were transformed again to TRUE and FALSE values within the all_star column.

Supplementary Sources

Refer to tutorials provide an explanation for learn how to carry out alternative familiar duties in R:

The best way to Take away Unfilled Rows from Knowledge Body in R
The best way to Take away Columns with NA Values in R
The best way to Take away Replica Rows in R

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *