I am having trouble doing a simple task:
Say I use these libraries and have this data frame:
library(tidyverse)
library(dataPreparation)
df <- data.frame(col1 = 1, col2 = rnorm(1e1), col3 = sample(c(1, 2), 1e1, replace = TRUE))
df$col4 <- df$col2
df$col5[df$col3 == 1] = "a"
df$col5[df$col3 == 2] = "b"
df$col6 = c("b","b","a","a","b","a","a","a","a","b")
df$col7 = "d"
df$col8 = c(3,3,5,5,3,5,5,5,5,3)
df$col9 = c("x","x","y","y","x","y","y","y","y","x")
df$col10 = c("p","p","q","p","q","q","p","p","q","q")
df$col11 = c(10.5,10.5,11.37,10.5,11.37,11.37,10.5,10.5,11.37,11.37)
df <- df %>% mutate_if(is.character,as.factor)
Using the below command,I want to remove the columns 4, 5, 7, 8, 9, 11 from df.
whichAreBijection(df)
[1] "whichAreBijection: col7 is a bijection of col1. I put it in drop list."
[1] "whichAreBijection: col4 is a bijection of col2. I put it in drop list."
[1] "whichAreBijection: col5 is a bijection of col3. I put it in drop list."
[1] "whichAreBijection: col8 is a bijection of col6. I put it in drop list."
[1] "whichAreBijection: col9 is a bijection of col6. I put it in drop list."
[1] "whichAreBijection: col11 is a bijection of col10. I put it in drop list."
[1] "whichAreBijection: it took me 0.08s to identify 6 column(s) to drop."
[1] 4 5 7 8 9 11
I can remove them manually by using
df$col4 = NULL
df$col5 = NULL
df$col7 = NULL
df$col8 = NULL
df$col9 = NULL
df$col11 = NULL
I want, however, the algorithm to automatically do it.
I tried the following first to generate the data frame m containing column numbers proposed by whichAreBijection and then eventually delete it from df, but it led me no where:
x <- whichAreBijection(df)
y <- length(x)
m <- as.data.frame(matrix(0, ncol = y, nrow = nrow(df)))
i = 1
while (i< y+1) {
# z <- names(df)[x[i]]
m[,i] <- df[,x[i]]
i<- i+1
}
The above generates m with constant entries given by 4, 5, 7, 8, 9, 11
I see that using a simple command like
m[,1] <- df[,4]
perfectly replaces the first column of m with the 4th column of df.
The second trouble that I have is using the same column names in m as in df. May be this sounds a long way to do the simple task.
Why are columns not being replaced exactly in m?
How could I automatically let m choose the column names of df to be deleted as column names?
Is there a better way to avoid this mess and do a straightforward removal of column names proposed by whichAreBijection?