Search code examples
rsapply

How to convert sapply code into vapply code


I have been told to try use of vapply() rather than sapply() for my code and functions. I use sapply() quite frequently, and am attempting to use vapply() instead but a few of my functions have fairly complex sapply() usage.

I give an example below, and would appreciate some guidance on how to regenerate the same outcome but with the use of vapply() rather than sapply().

> dput(head(df[1]))
structure(list(D1 = structure(c(WP1 = 47L, WP10 = 17L, WP103 = 21L, 
WP108 = 23L, WP113 = 34L, WP116 = 79L), .Label = c("  0.00", 
"  0.57", " 10.00", "100.00", " 10.20", " 10.26", " 10.34", " 10.53", 
" 10.87", " 11.11", " 11.36", " 11.48", " 11.54", " 11.76", " 11.94", 
" 12.20", " 12.50", " 12.86", " 12.90", "  1.30", " 13.33", " 13.43", 
" 13.46", " 13.64", " 13.73", " 13.75", " 14.00", " 14.29", " 14.63", 
" 14.75", "  1.49", " 15.00", " 15.28", " 15.38", " 15.62", " 15.79", 
"  1.60", " 16.13", " 16.67", " 17.39", " 17.95", " 18.18", " 18.75", 
" 18.97", " 19.05", " 19.44", " 20.00", " 20.20", " 20.59", " 22.03", 
" 22.22", " 22.73", " 23.08", " 23.53", "  2.38", " 24.14", " 25.00", 
" 26.09", "  2.62", " 26.32", " 27.59", "  2.86", " 29.03", "  2.94", 
"  3.23", " 32.69", "  3.30", "  3.33", " 33.33", " 37.50", "  3.85", 
"  3.90", "  3.96", "  4.00", "  4.35", "  4.44", "  4.46", "  4.51", 
"  4.55", "  4.64", "  4.71", "  4.88", " 50.00", "  5.33", "  5.48", 
"  5.88", "  6.07", "  6.19", "  6.22", "  6.38", "  6.63", "  6.67", 
"  6.82", "  6.84", "  6.90", "  6.91", "  7.14", "  7.17", "  7.25", 
" 75.00", "  7.55", "  7.69", "  7.89", "  8.00", "  8.04", "  8.11", 
"  8.33", "  8.43", "  8.57", "  9.09", "  9.52", "  9.93"), class = "factor")), row.names = c("WP1", 
"WP10", "WP103", "WP108", "WP113", "WP116"), class = "data.frame")

This is a dataframe of factors which I convert into a dataframe of numerics using the following code.

df[sapply(df, is.factor)] <- lapply(df[sapply(df, is.factor)],
        function(x) as.numeric(as.character(x)))

With vapply() I would have to provide the output I am looking for, would I include this in both calls of sapply()?

Any help or guidance would be appreciated.


Solution

  • Replace sapply with:

    vapply(df, is.factor, logical(1))