Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

In the R cli I am able to do the following on a character column in a data frame:

> data.frame$column.name [data.frame$column.name == "true"] <- 1 > data.frame$column.name [data.frame$column.name == "false"] <- 0 > data.frame$column.name <- as.integer(data.frame$column.name) 

I would like to do this as a function and I tried the following code, inputing data.frame$column.name as arg1. I see that it is working when I return(arg1) but how do I return the operation to the original data.frame?

boolean.integer <- function(arg1) {   arg1 [arg1 == "true"] <- 1   arg1 [arg1 == "false"] <- 0   arg1 <- as.integer(arg1) } 
like image 901
DecisionNerd Avatar asked Nov 26 '15 03:11

DecisionNerd


People also ask

How do you change true/false to 1 0 in Python?

In Python True and False are equivalent to 1 and 0. Use the int() method on a boolean to get its int values. int() turns the boolean into 1 or 0. Note: that any value not equal to 'true' will result in 0 being returned.

How do I change DataFrame column values based on conditions?

You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.

How do you assign a value to a DataFrame column?

DataFrame - assign() function The assign() function is used to assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. The column names are keywords.

How do you convert boolean to int in Python?

To convert boolean to integer in python, we will use int(bool) and then it will be converted to integer.


1 Answers

@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))

like image 87
DecisionNerd Avatar answered Sep 19 '22 17:09

DecisionNerd