r - Accessing data frame columns via names using regex -


i have huge data.frame [350000, 431] , need cleaning on it. 1 of cleaning operation turn boolean columns c(0,1) c(false, true). can identify these columns condition column name contains string "include". need that:

data.clean[,4:272] <-  ifelse(data.clean[,4:275] == 1,"true", "false") 

where instead of 4:272 (index of columns contains "include", want use more robust regex purpose.

mimic data (only 3 columns, 2 columns meeting "include" condition"):

data.clean <- data.frame(exclude = sample(letters, 3.5e5, replace=true), this.include = sample(c(0,1), 3.5e5, replace=true), this.include2=sample(c(0,1), 3.5e5, replace=true))  > head(data.clean)   exclude this.include this.include2 1       w            1             1 2       y            1             0 3       f            0             0 4       w            0             1 5       b            1             0 6       m            1             1 

use names , grep identify correct columns, , use direct logical comparison return values true , false:

data.clean[,names(data.clean)[grep("include", names(data.clean))]] <- data.clean[,names(data.clean)[grep("include", names(data.clean))]] == 1  > head(data.clean)   exclude this.include this.include2 1       w         true          true 2       y         true         false 3       f        false         false 4       w        false          true 5       b         true         false 6       m         true          true 

Comments

Popular posts from this blog

Why can rails not find a route created by a helper? -

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -