r - 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
解决方案
你想要更像这样的东西:
#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 行增长数据帧将在数据帧开始后开始产生显着的速度损失相当大。
推荐阅读
- java - Soft-/Weak-/PhantomReferences 清除对已引用跟踪对象的对象的引用的基本原理
- xamarin.forms - Navigation.PopAsync 与 PushModalAsync?
- node.js - 电子错误错误:找不到模块“mysql”需要堆栈:
- android - TextView autoSizeTextType 在应用小部件中不起作用
- jquery - WP滑动条切换无法关闭抽屉
- excel - 按最小值(最小值)+连接对excel中的行进行排序
- arrays - 如何在 Julia 中按行压缩 2D 和 1D 数组?
- python - 找到所有的美丽汤只给出最后一个结果
- c++ - 为什么这个简单的八卦脚本不起作用?
- haskell - “广义箭头”和 proc 符号?