![](/img/trans.png)
[英]How to get values of a numeric column with column name as a parameter in a for loop in R
[英]R get column name in loop
這聽起來應該很容易,但我找不到如何在 R 中執行此操作。如何循環遍歷數據幀的所有列並將列名和其他值(標簽列值)添加到新數據幀? 下面代碼中的數據框df
是一個現有的數據框,只包含數字列和一個label
特征(只有 0 或 1 個值)。 在下面的代碼中, colnames(i)
部分不起作用,因為它需要一個列表。 如何在循環中打印i
的列名? for 循環中的biserial.cor(i, df$label)
函數需要兩個參數。 第一個需要是數字向量,第二個應該是布爾向量(只有 0 或 1)。 因此bis.cor.table
的預期結果應如下所示:
colname corrWithLabel
col1 0.45
col2 0.12
col3 0.8
#Create new dataframe
bis.cor.table = data.frame(colname = character(),
corrWithLabel = numeric())
#Loop trough df and add values to dataframe bis.cor.table
for(i in = df) {
new.df = data.frame(colnames(i), biserial.cor(i, df$label))
names(de) = c("colname", "corrWithLabel")
bis.cor.table = r.bind(bis.cor.table, new.df)
}
看起來你的代碼中有很多錯別字,但我想我理解邏輯。 通過修復它們,這就是我所擁有的:
df = data.frame(col1 = runif(10),
col2 = runif(10),
col3 = runif(10),
label = sample(c(0,1), size = 10, replace = TRUE))
#Create new dataframe
bis.cor.table = data.frame(colname = character(),
corrWithLabel = numeric())
#Loop trough df and add values to dataframe bis.cor.table
for(i in 1:ncol(df)) {
new.df = data.frame(colnames(df)[i], biserial.cor(df[i], df$label))
names(new.df) = c("colname", "corrWithLabel")
bis.cor.table = rbind(bis.cor.table, new.df)
}
雖然不確定這是最好的方法,但我無法測試結果是否准確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.