当我输入列名时,我的代码运行良好。但是,当我想用列名的向量创建一个循环并通过对列进行索引来对数据框进行排序时,它无法正常工作。
以下代码效果很好:
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函数在循环内部不起作用,就像在循环外部一样。
答案 0 :(得分:1)
i
未评估。我们可能需要get
或转换为symbol
和eval
在循环内完成
...
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])]
}