Convert the data column to 1 or 0 for true / false values ​​and assign to dataframe

In R cli, I can do the following in 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 by entering data.frame $ column.name as arg1. I see that it works when I return (arg1), but how to return the operation to the original data.frame file?

boolean.integer <- function(arg1) {
  arg1 [arg1 == "true"] <- 1
  arg1 [arg1 == "false"] <- 0
  arg1 <- as.integer(arg1)
}
+4
source share
4 answers

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

+13
source

You can try if.else

> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true"  "false"

> cbind(df1$col)
     [,1]   
[1,] "true" 
[2,] "false"
> cbind(df1$col,col2)
             col2
[1,] "true"  "1" 
[2,] "false" "0" 
+1
source

Since you are dealing with values ​​that should be logical anyway, just use ==and convert the logical answer to as.integer:

df <- data.frame(col = c("true", "true", "false"))
df
#     col
# 1  true
# 2  true
# 3 false
df$col <- as.integer(df$col == "true")
df
#   col
# 1   1
# 2   1
# 3   0
0
source

Try this, it converts True to 1 and False to 0:

data.frame$column.name.num  <- as.nunumeric(data.frame$column.name)

Then you can convert to a coefficient if you want:

data.frame$column.name.num.factor <- as .factor(data.frame$column.name.num)
0
source

Source: https://habr.com/ru/post/1617545/


All Articles