I have a dataset like this :
id value1 value2
1 A True
2 B False
3 A True
4 C True
I want to identify a column with multiple values and convert it into multiple columns with True or False values in R. The result would be :
id value1.A value1.B value1.C value2
1 True False False True
2 False True False False
3 True False False True
4 False True False True
I am not sure how to use dcast for this. I wrote a function myself but it is too slow. The code for it is here :
to_multiple_columns <- function(col,attr_name){
elements <- names(table(col))
drops <- c("","True","False")
elements <- elements[ !elements %in% drops]
new_df <- data.frame(col) # to define data frame with nrows,ncols
if(length(elements) > 0){
new_attr_names <- paste(attr_name,elements,sep = ".")
for(j in 1:length(new_attr_names)){
new_df <- data.frame(new_df,grepl(elements[j],col))
}
drops <- c("col") #drop original col
new_df <- new_df[,!(names(new_df) %in% drops)]
names(new_df) <- new_attr_names
}
return(new_df)
}