简体   繁体   中英

Looping through R dataframe columns

I want to loop a dataframe columns and use them for something else (in this case, performing a chi-squared test on all my features.

for(i in (1:ncol(wdbc))){
  wdbc[,i]
  chisq.test(wdbc$diagnosis,wdbc[,i])
}

I've tried referring to the features in all kinds of ways, for example:

chisq.test(wdbc$diagnosis,wdbc[i]) ##looping through colnames(wdbc)

or

chisq.test(wdbc$diagnosis,wdbc$i) ##looping through colnames(wdbc)

but can't seem to solve the problem.

wdbc[i] will return a dataframe (rather than a vector), and wdbc$i doesn't work to loop through column names.

wdbc[,i] should work if wdbc is actually a dataframe. However, I've encountered an error in this type of situation before when my dataframe is not actually a dataframe but a tibble. The issue is that wdbc[,i] will still be a tibble rather than a vector. Try converting it to a dataframe with as.data.frame(wdbc) .

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