【问题标题】:r - levels added to dataframe, why?r - 添加到数据框的级别,为什么?
【发布时间】:2018-07-16 20:38:43
【问题描述】:

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

考虑以下简短脚本,我在其中计算随机数据帧 df 的每一列的 RMSE,并将值存储为新数据帧 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() 造成的吗?

这也会产生其他问题。比如order函数不起作用。

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

【问题讨论】:

  • 正因如此:as.data.frame(cbind( RMSE, toString(row_num) )) 这是创建数据帧的一种常见习语,非常不明智。只需改用data.frame()cbind 将事物强制为单一类型,字符。
  • 另外,你真的想使用as.character,而不是toString。如果您阅读文档,这个名称有点误导。
  • 谢谢。但是,即使从 as.data.frame 中删除“as”,“级别”仍然存在。而且下单还是不行。
  • 请参阅下面的答案以获取更多上下文。

标签: r rbind levels


【解决方案1】:

你想要更像这样的东西:

#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)
}

为了完整起见,我要补充一点,虽然这不是您的问题的重点,但像这样一次将数据帧增加rbindind 行将开始产生显着 一旦数据帧变得相当大,速度就会下降。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2018-08-26
    • 2016-09-17
    • 1970-01-01
    • 2020-10-19
    • 2021-08-31
    • 2019-02-28
    相关资源
    最近更新 更多