简体   繁体   中英

Loop over columns of dataframe in R

How can I loop to perform the same test over columns with similar names in R?

for example I have three columns, named col30, col126, col145. I was thinking something like:

x <- c(30, 126, 145)

for (i in x) {

  wilcox.test(col(i) ~ level)

}

is not working and provide the following error:

Error in eval(predvars, data, env) : attempt to apply non-function

Here is a dplyr example:

library(tidyverse)

df %>%
    summarise_at(vars(col30, col126, col145), wilcox.test, y = level)

您可以使用apply函数而不是for loop并对所选列迭代相同的测试:

apply(df[, c(col30, col126, col145)], 2, wilcox.test ~ level)

x <- c(30, 126, 145)
for (i in x) {
    wilcox.test(df[,i] ~ level)
}

where df is your data frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM