0

I have a df, I would like to create a function which read and modify a whole column if the columnnname contains a specific characteristica, eg. '(str)'. If the columnname contains '(str)' I would like "'%" and "%'" to be pasted before and after the values in the whole column

#create df
y<- data.frame('criteria1' = c('info','1', 'info', '', 'info'), "criteria2.(str)" = c('y','3', '', 'info', ''), "criteria3" = c('y','7', '', 'info', 'info'), check.names=FALSE)

the expected result is:

y1<- data.frame('criteria1' = c('info','1', 'info', '', 'info'), "criteria2.(str)" = c("'%y%'","'%3%'", "'%%'", "'%info%'", "'%%'"), "criteria3" = c('y','7', '', 'info', 'info'), check.names=FALSE)

I have tried with lapply without luck

 y[]<- lapply(y, function(x) 
                      ifelse(colnames(y)[x] %like% ('(str)'), 
                             paste0("'%",x,"%'"),  x))

 y[]<- lapply(y, function(x) 
                      ifelse(colnames(y) %like% ('(str)'), 
                             paste0("'%",x,"%'"),  x))

with sapply '%x%' is added horizontally, but not for the column

y <- sapply(1:ncol(y), function(x) 
  ifelse(colnames(y) %like% ('.(str)'),  paste0("'%",x,"%'"),  x))

Thanks a lot in advance!

aynber
  • 22,380
  • 8
  • 50
  • 63
Mette
  • 315
  • 1
  • 3
  • 12

2 Answers2

2

Using data.table and stringr will do the job. You can modify the target columns within str_detect().

Does this work?

library(data.table)
library(stringr)

y <- data.table('criteria1' = c('info','1', 'info', '', 'info'), 
               "criteria2.(str)" = c('y','3', '', 'info', ''), 
               "criteria3" = c('y','7', '', 'info', 'info'), 
               check.names=FALSE)

towrangle <- names( y )[str_detect( names(y), "\\(str\\)")]

y[ , (towrangle) := lapply(.SD, function( x ) str_c( "\'%", x, "%\'") ), 
   .SDcols = towrangle ]
y
#>    criteria1 criteria2.(str) criteria3
#> 1:      info           '%y%'         y
#> 2:         1           '%3%'         7
#> 3:      info            '%%'          
#> 4:                  '%info%'      info
#> 5:      info            '%%'      info

Created on 2021-03-04 by the reprex package (v1.0.0)

Francesco Grossetti
  • 1,555
  • 9
  • 17
0

another data.table approach

basically the same as the answer from Francesco (who was a bit sonner with his answer)... Only selection of columns (and pasting strings) differs, so package stringr is not needed..

library( data.table )
setDT(y)
cols <- grep( "\\(str\\)", names(y), value = TRUE )
#update
y[, (cols) := lapply( .SD, function(x) paste0( "%", x, "%" ) ), .SDcols = cols ][]

#    criteria1 criteria2.(str) criteria3
# 1:      info             %y%         y
# 2:         1             %3%         7
# 3:      info              %%          
# 4:                    %info%      info
# 5:      info              %%      info
Wimpel
  • 26,031
  • 1
  • 20
  • 37