I try to create a function that checks the data frame to detect the binary vectors (columns) and changes these binary vectors into factors. I have managed to design a code. However, when I tried to wrap it into a function, the function did not work. My question is: what is wrong with my function, and what is missing?
data(mtcars)
df=mtcars
Col_Name=c()#creating an empty vector
for (i in 1:ncol(df)) {
if (is.numeric(df[,i])){
Col_Name[i] <- colnames(df)[i]
} #checking the columns and collecting the numeric columns into a vector
}
Col_Name <- na.omit(Col_Name)#removing the NA
for (col in 1:length(Col_Name)) {
bi=unique(df[,col])#detecting the unique variables.
if (is.numeric(bi)) {
bi2=all(bi%in%c(0,1))#cheking if the unique variable contains 0 and 1
if (bi2==TRUE) df[,col] <- as.factor(df[,col])#changing the column into a factor
}
}#the function is supposed to return nothing. however when checking the data frame, 0,1 columns change into factor.
str(df)#check the impact of the code.
Now, let’s wrap the code into a function.
My_binary=function(df){Col_Name=c()
for (i in 1:ncol(df)) {
if (is.numeric(df[,i])){
Col_Name[i] <- colnames(df)[i]
}
}
Col_Name <- na.omit(Col_Name)
for (col in 1:length(Col_Name)) {
bi=unique(df[,col])
if (is.numeric(bi)) {
bi2=all(bi%in%c(0,1))
if (bi2==TRUE) df[,col] <- as.factor(df[,col])
}
}}
str(df) #return nothing>>>>
I have tried to run the function, but it returned nothing. I understand that something is missing. However, I can’t figure out what.