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!
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