简体   繁体   English

循环遍历 R dataframe 列

[英]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.我想循环 dataframe 列并将它们用于其他用途(在本例中,对我的所有功能执行卡方检验。

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]将返回 dataframe(而不是向量),并且wdbc$i无法循环遍历列名。

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.如果wdbc实际上是 dataframe, wdbc[,i]应该可以工作。但是,我之前在这种情况下遇到过错误,当时我的 dataframe 实际上不是 dataframe,而是一个 tibble。 The issue is that wdbc[,i] will still be a tibble rather than a vector.问题是wdbc[,i]仍然是一个 tibble 而不是一个向量。 Try converting it to a dataframe with as.data.frame(wdbc) .尝试使用as.data.frame(wdbc)将其转换为 dataframe。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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