首页 > 解决方案 > r - 添加到数据框的级别,为什么?

问题描述

这篇文章是为了更好地理解“级别”在 R 中是如何工作的。事实上,其他答案并没有完全解释(例如参见this)。

考虑以下简短脚本,我在其中计算随机数据帧的每一列的 RMSE,df并将该值存储为新数据帧的一行bestcombo

df = as.data.frame(matrix(rbinom(10*1000, 1, .5), nrow = 10, ncol=5))

#generate empty dataframe and assign col names
bestcombo = data.frame(matrix(ncol = 2, nrow = 0))
colnames(bestcombo) = c("RMSE", "Row Number")

#for each col of df calculate RMSE and store together with col name
for (i in 1:5){
  RMSE = sqrt(mean(df[,i] ^ 2))
  row_num = i

  row = as.data.frame(cbind( RMSE, toString(row_num) ))
  colnames(row) = c("RMSE", "Row Number")
  bestcombo = rbind(bestcombo, row)
}

问题是生成了“级别”。为什么?

bestcombo$RMSE
             RMSE              RMSE              RMSE              RMSE              RMSE 
0.547722557505166 0.774596669241483 0.707106781186548 0.836660026534076 0.707106781186548 
Levels: 0.547722557505166 0.774596669241483 0.707106781186548 0.836660026534076

bestcombo$RMSE[1]
             RMSE 
0.547722557505166 
Levels: 0.547722557505166 0.774596669241483 0.707106781186548 0.836660026534076

为什么会发生这种情况以及如何避免?这是由于错误使用 rbind() 造成的吗?

这也会产生其他问题。例如,订单功能不起作用。

bestcombo[order(bestcombo$RMSE),]

               RMSE Random Vector
1 0.547722557505166             1
2 0.774596669241483             2
3 0.707106781186548             3
5 0.707106781186548             5
4 0.836660026534076             4

标签: rrbindlevels

解决方案


你想要更像这样的东西:

#for each col of df calculate RMSE and store together with col name
for (i in 1:5){
    RMSE = sqrt(mean(df[,i] ^ 2))
    row_num = i

    row = data.frame(RMSE = RMSE, `Row Number` = as.character(row_num) )
    #colnames(row) = c("RMSE", "Row Number")
    bestcombo = rbind(bestcombo, row)
}

或者,如果你真的想在第二行添加列名,你可以这样做:

for (i in 1:5){
    RMSE = sqrt(mean(df[,i] ^ 2))
    row_num = i

    row = data.frame(RMSE,as.character(row_num) )
    colnames(row) = c("RMSE", "Row Number")
    bestcombo = rbind(bestcombo, row)
}

只是为了完整起见,我要补充一点,虽然这不是您问题的重点,但rbind像这样一次一个地按 ind 行增长数据帧将在数据帧开始后开始产生显着的速度损失相当大。


推荐阅读