I have a list of lists (2 df's) and want to use lapply to perform the same function for pre-defined columns in each df.
In particular I would like to use the winsorize function from the DescTools package. At the moment I know how to do this by specifying all individual columns within the function(x) command, which is, however, tedious if I have many columns (see example).
After applying the function, the entire list of lists (all columns) with the transformed variables should be returned. Ideally, the transformed variables are extended with "_w" (e.g. "price_w") or similar to indicate that these are the winsorized variables.
My data looks as follows, although I want to apply the function only to the pre-defined columns "price" and "quality".
id <- c(1, 5, 7, 9, 12)
country <- c("A", "A", "C", "E", "E")
price <- c(2.1, 4.6, 3.7, 2.9, 1.8)
quality <- c(3.1, 5.2, 3.3, 1.7, 0.9)
df1 <- cbind.data.frame(id, country, price, quality)
id <- c(2, 3, 4, 10, 14)
country <- c("F", "F", "A", "Z", "X")
price <- c(1.8, 5.2, 2.9, 4.6, 3.9)
quality <- c(4.3, 2.5, 6.9, 1.9, 0.8)
df2 <- cbind.data.frame(id, country, price, quality)
my.list <- list(df1, df2)
cols <- c("price", "quality")
This is what I have so far, which would only work for a small number of columns due to the necessary manual changes:
my.list <- lapply(my.list, function(x) {
x$price_w <- DescTools::Winsorize(x$price, probs = c(.01, .99), na.rm = TRUE)
x$quality_w <- DescTools::Winsorize(x$quality, probs = c(.01, .99), na.rm = TRUE)
return(x)
})