Josh Bullers
Josh Bullers

Reputation: 13

Coerce columns of a data frame to be logical based on column values

I have a data set that has around 200 columns. On the import, columns with logical TRUE, FALSE values get coerced to character.

     Col1     Col2     Col3      .      .      .
1    "A"      100     "TRUE"
2    "B"      110     "FALSE"
3    "C"      120     "FALSE"
4    "D"      130     "TRUE"
.
.
.

Given the above data frame example, it seems I could coerce it back using something like as.logical(df$Col3) but this would be highly manual to go through all 200+ columns changing the TRUE, FALSE columns to logical.

Is it possible to conditionally select columns from the entire data frame, based on the values of the column, and convert those columns to a logical data type?

Upvotes: 1

Views: 465

Answers (1)

josliber
josliber

Reputation: 44330

You could identify if each column should be converted with:

(to.conv <- sapply(dat, function(x) all(x %in% c("FALSE", "TRUE"))))
#  Col1  Col2  Col3  Col4 
# FALSE  TRUE FALSE  TRUE 

Then you can convert the relevant columns to the logical type:

dat[,to.conv] <- sapply(dat[,to.conv], as.logical)
str(dat)
# 'data.frame': 3 obs. of  4 variables:
#  $ Col1: chr  "a" "b" "c"
#  $ Col2: logi  TRUE FALSE TRUE
#  $ Col3: chr  "a" "b" "c"
#  $ Col4: logi  TRUE TRUE TRUE

Original data:

dat <- data.frame(Col1=c("a", "b", "c"), Col2=c("TRUE", "FALSE", "TRUE"), Col3=c("a", "b", "c"), Col4=c("TRUE", "TRUE", "TRUE"), stringsAsFactors=F)
str(dat)
# 'data.frame': 3 obs. of  4 variables:
#  $ Col1: chr  "a" "b" "c"
#  $ Col2: chr  "TRUE" "FALSE" "TRUE"
#  $ Col3: chr  "a" "b" "c"
#  $ Col4: chr  "TRUE" "TRUE" "TRUE"

Upvotes: 1

Related Questions