Shivpe_R Shivpe_R - 11 days ago 5
R Question

Apply Function to create dataset from the dataframes column

I have a dataset as shown below

Given Dataset

The challenge is to apply function on the columns from the 3rd column till the end.
The Function should Filter the dataset, column having only false and create a dataframe by the name as column name as shown below for the 3rd and 4th columns
and there are lot of columns available,i have to use apply function. can anyone give a solution.

Dataframe from 3rd column
Dataframe from 4th column

and so on for the rest of the columns.

Answer

We can use Map to create a list of 'data.frame`s

nm1 <- names(df1)[3:ncol(df1)]
lst <- setNames(Map(function(x,y) {
               x1 <- cbind(df1[1:2], x)[!x,]
               names(x1)[3] <- y
               x1 },
          df1[3:ncol(df1)], nm1), nm1) 
lst
#$LOGICCOLUMN1
#  COLUMN1 COLUMN2 LOGICCOLUMN1
#6    FFFF    jjjj        FALSE
#8    HHHH    BBBB        FALSE

#$LOGICCOLUMN2
#  COLUMN1 COLUMN2 LOGICCOLUMN2
#1    AAAA    EEEE        FALSE
#4    DDDD    HHHH        FALSE
#5    EEEE    llll        FALSE

#$LOGICCOLUMN3
#   COLUMN1 COLUMN2 LOGICCOLUMN3
#2     BBBB    FFFF        FALSE
#8     HHHH    BBBB        FALSE
#10    jjjj    DDDD        FALSE

It is better to keep it as a list. But if we really need to have objects in the global environment (not recommended)

list2env(lst, .GlobalEnv)
LOGICCOLUMN1
#  COLUMN1 COLUMN2 LOGICCOLUMN1
#6    FFFF    jjjj        FALSE
#8    HHHH    BBBB        FALSE

data

df1 <- structure(list(COLUMN1 = c("AAAA", "BBBB", "CCCC", "DDDD", "EEEE", 
"FFFF", "GGGG", "HHHH", "llll", "jjjj"), COLUMN2 = c("EEEE", 
"FFFF", "GGGG", "HHHH", "llll", "jjjj", "AAAA", "BBBB", "CCCC", 
"DDDD"), LOGICCOLUMN1 = c(TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, 
TRUE, FALSE, TRUE, TRUE), LOGICCOLUMN2 = c(FALSE, TRUE, TRUE, 
FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE), LOGICCOLUMN3 = c(TRUE, 
FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE)), .Names = c("COLUMN1", 
"COLUMN2", "LOGICCOLUMN1", "LOGICCOLUMN2", "LOGICCOLUMN3"), row.names = c(NA, 
-10L), class = "data.frame")