【问题标题】:Subsetting and Indexing in For Loop in RR中的For循环中的子集和索引
【发布时间】:2015-08-14 09:03:31
【问题描述】:

我正在尝试收集按排名排序的数据集中的 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==["

【问题讨论】:

  • 您的函数没有返回值。您能否包含显示您打算如何使用它的代码?
  • testscript(3) 应该产生:State City Value Rank 3 State1 city3 0.05694883 1 13 State2 city3 0.08323056 1 5 State1 city5 0.3006471 2 16 State2 city6 0.1483099 2 1 State1 city1 0.3988151 3 17 State2 /跨度>

标签: r for-loop indexing minimum


【解决方案1】:

如果您想获得按排名排序的数据集中的 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

【讨论】:

  • 为什么不只是head(df[order(df$Rank), ])num 是干什么用的?
  • @Maiasaura num 表示要取的行数。
  • 我希望能够指定最小值的个数。
  • @LeeorShimron 更改 num 以指示您想要的最小值的数量。在我的示例中设置为 10。
  • @josilber 谢谢!这似乎行得通。不过,我仍然很好奇为什么 for 循环不起作用。
猜你喜欢
  • 2021-06-23
  • 2017-04-20
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多