Given a data frame:
l$`__a` <- data.frame(`__ID` = stringi::stri_rand_strings(10, 1),
col = stringi::stri_rand_strings(10, 1), check.names = F )
And two supporting functions:
prefixColABC <- function(dfCol) {
paste0("ABC_", dfCol)
}
prefixColDEF <- function(dfCol) {
paste0("DEF_", dfCol)
}
How can I apply the first function for data frame column names staring with __ and the second for all other columns?
To solve this problem, I thought I would subset first all columns with names starting with __, apply prefixColABC to them, then subset all others and apply prefixColDEF to them. Then I would use cbind() to put all of the columns together into one data frame again.
Here's some of my progress:
Here's how the first function can be applied to all columns:
as.data.frame( apply(l$`__a`, 2, prefixColABC) )
And here's how I can subset the columns. All with column names starting with __:
l$`__a`[ grep(pattern = "^__", l$`__a`), 1 ]
I don't know how to subset all other columns that don't match this pattern. And I don't know how to set up the condition inside the apply statement
I think this question is similar to mine, but does not select the columns based on matching a pattern: R Applying different functions to different data frame columns