Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe
@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))
Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.
Example given
df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE,
NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA,
TRUE), p1_3 = c(TRUE,
TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA,
FALSE, FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA,
FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA,
FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA,
FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE,
FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE,
FALSE, NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE,
FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE,
FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names =
c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6",
"p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names =
c(NA, -7L), class = "data.frame")
p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1 TRUE FALSE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE FALSE
2 FALSE TRUE TRUE NA NA NA NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE NA NA NA NA
4 NA NA NA FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE
5 TRUE FALSE NA TRUE FALSE FALSE NA TRUE FALSE FALSE NA
6 FALSE NA FALSE FALSE NA NA FALSE FALSE NA NA FALSE
7 NA TRUE TRUE NA TRUE TRUE TRUE NA TRUE TRUE TRUE
Then by running that: df * 1
all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).
> df*1
p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1 1 0 1 0 1 1 1 0 1 1 0
2 0 1 1 NA NA NA NA 0 0 0 0
3 0 0 0 0 0 0 0 NA NA NA NA
4 NA NA NA 0 1 1 1 0 0 0 0
5 1 0 NA 1 0 0 NA 1 0 0 NA
6 0 NA 0 0 NA NA 0 0 NA NA 0
7 NA 1 1 NA 1 1 1 NA 1 1 1
I do not know if it a total "safe" command, under all different conditions / dfs.
can you 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"