sapply
Create frequency tables for multiple factor columns in R
You were nearly there. Just one small change in your function would have got you there. The x in function(x) … needs to be passed through to the table() call: levs <- c(“Not Impt at all”, “Somewhat Impt”, “Neutral”, “Impt”, “Very Impt”) sapply(x.sample, function(x) table(factor(x, levels=levs, ordered=TRUE))) A little re-jig of the code might make … Read more
Means multiple columns by multiple groups [duplicate]
We can use dplyr with summarise_at to get mean of the concerned columns after grouping by the column of interest library(dplyr) airquality %>% group_by(City, year) %>% summarise_at(vars(“PM25”, “Ozone”, “CO2”), mean) Or using the devel version of dplyr (version – ‘0.8.99.9000’) airquality %>% group_by(City, year) %>% summarise(across(PM25:CO2, mean))
Apply a function to every row of a matrix or a data frame
You simply use the apply() function: R> M <- matrix(1:6, nrow=3, byrow=TRUE) R> M [,1] [,2] [1,] 1 2 [2,] 3 4 [3,] 5 6 R> apply(M, 1, function(x) 2*x[1]+x[2]) [1] 4 10 16 R> This takes a matrix and applies a (silly) function to each row. You pass extra arguments to the function as … Read more
Concatenate row-wise across specific columns of dataframe
Try data$id <- paste(data$F, data$E, data$D, data$C, sep=”_”) instead. The beauty of vectorized code is that you do not need row-by-row loops, or loop-equivalent *apply functions. Edit Even better is data <- within(data, id <- paste(F, E, D, C, sep=””))
Grouping functions (tapply, by, aggregate) and the *apply family
R has many *apply functions which are ably described in the help files (e.g. ?apply). There are enough of them, though, that beginning useRs may have difficulty deciding which one is appropriate for their situation or even remembering them all. They may have a general sense that “I should be using an *apply function here”, … Read more