R 中 For 循环的子集和索引

Subsetting and Indexing in For Loop in R

我正在尝试收集按排名排序的数据集中的 n 个最小值。

这是我的代码:

testscript <- function(num) {
    df <- data.frame(State = paste0("State",sort(rep(1:2,10))),
                     City = rep(paste0("city",rep(1:10,2))),
                     Value = runif(n=20))
    vec <- NULL
    df$Rank <- ave(df$Value, df$State, FUN=rank)
    for (i in 1:num) {
         vec[i] <- df[df$Rank==[i],]
    }
}

参数 num 是我要收集的最小值的个数。

当我 运行 函数时,出现以下错误:

    Error: unexpected '[' in:
    "for (i in 1:num) {
          vec[i] <- df[df$Rank==["

如果你想获得按排名排序的数据集中的 n 个最小值,你可以使用 orderhead 函数来实现——不需要 for 循环:

num <- 10
head(df[order(df$Rank),], num)
#     State   City        Value Rank
# 7  State1  city7 0.1075155728    1
# 19 State2  city9 0.0008769566    1
# 5  State1  city5 0.2829263743    2
# 17 State2  city7 0.0407836910    2
# 6  State1  city6 0.4697333111    3
# 14 State2  city4 0.1197360896    3
# 3  State1  city3 0.4853360290    4
# 11 State2  city1 0.1766399497    4
# 10 State1 city10 0.5803764823    5
# 13 State2  city3 0.3109590847    5