如何在索引中使用dataframe(datatable)姓氏向量对索引进行排序?

时间:2019-05-15 18:59:43

标签: r

当我输入列名时,我的代码运行良好。但是,当我想用​​列名的向量创建一个循环并通过对列进行索引来对数据框进行排序时,它无法正常工作。

以下代码效果很好:

indexROW <- round(nrow(Home_strategy_Yes) * 0.2)
Home_strategy_Yes_reordered <- Home_strategy_Yes[order(HT.av.points)]
Home_strategy_Yes_reordered$ID <- seq.int(nrow(Home_strategy_Yes_reordered))
value <- Home_strategy_Yes_reordered[indexROW,HT.av.points]
percentageTOfilter <- min(Home_strategy_Yes_reordered[HT.av.points == value,ID]) -1
valueTOfilter <- Home_strategy_Yes_reordered[percentageTOfilter,HT.av.points]

使用姓氏向量循环时的问题

columns_setA <- c("HT.av.points","HT_av.PointsTotal")
for (i in 1:length(columns_setA)){
  indexROW <- round(nrow(Home_strategy_Yes) * 0.2)
  Home_strategy_Yes_reordered <- Home_strategy_Yes[order(columns_setA[i])]
  Home_strategy_Yes_reordered$ID <- seq.int(nrow(Home_strategy_Yes_reordered))
  value <- Home_strategy_Yes_reordered[indexROW,columns_setA[i]]
  percentageTOfilter <- min(Home_strategy_Yes_reordered[columns_setA[i] == value,ID]) -1
  valueTOfilter <- Home_strategy_Yes_reordered[percentageTOfilter,columns_setA[i]]

}  

order函数在循环内部不起作用,就像在循环外部一样。

2 个答案:

答案 0 :(得分:1)

i未评估。我们可能需要get或转换为symboleval在循环内完成

...
percentageTOfilter <- min(Home_strategy_Yes_reordered[get(i) == value,ID]) -1
...

答案 1 :(得分:0)

添加get()订单函数按预期工作。

for (i in 1:length(columns_setA)){
  indexROW <- round(nrow(Home_strategy_Yes) * 0.2)
  Home_strategy_Yes_reordered <- Home_strategy_Yes[order(get(columns_setA[i]))]
  Home_strategy_Yes_reordered$ID <- seq.int(nrow(Home_strategy_Yes_reordered))
  value <- Home_strategy_Yes_reordered[indexROW,get(columns_setA[i])]
  percentageTOfilter <- min(Home_strategy_Yes_reordered[get(columns_setA[i]) == value,ID]) -1
  valueTOfilter <- Home_strategy_Yes_reordered[percentageTOfilter,get(columns_setA[i])]

}