【问题标题】:R: Get indices of all elements in a vector?R:获取向量中所有元素的索引?
【发布时间】:2018-03-22 20:58:42
【问题描述】:

简单的问题,但我找不到答案。

我有一个向量

a<-c(5,6,7)

如何取回向量中所有元素的索引?

我需要回来

1  #"a"
2  #"b"
3  #"c"

c(1,2,3)

如果我运行 seq_along(a),它会返回 (1,1,1) 而不是 (1,2,3)

for (i in seq_along(a)) {
  print(seq_along(a[[i]])) 
}

[1] 1
[1] 1
[1] 1

这样做的原因是我需要为我的每个地块创建一个唯一的名称。我有大约 100 个地块,说明了 100 个位置。位置的名称太长并且包含特殊字符,因此我不能使用它们来命名我的输出图。我想使用索引值来替换每个保存的绘图的名称。

我需要修改的函数:

lineCumRateGraph <- function(tab, na.rm = TRUE, ...) {

  # Create list of locations
  type_list <-unique(tab$uniqueLoc)

  # Create a for loop to produce ggplot plots
  for (i in seq_along(type_list)) {

    # create a plot for each loc in df
    plot<-

      ggplot(subset(tab, tab$uniqueLoc == type_list[i]),
             aes(x = factor(gridcode), 
                 y = cumRate) +
      geom_line(aes(linetype = distance),
                size = 1) +
      ggtitle(type_list[i])

    windows(width = 4, height = 3.5)
    print(plot)
    ggsave(plot,
           width = 3.5, height = 3.5,
           file = paste(outPath,
                        "lineCumRate",
                       # type_list[i], # I need to replace this one by index value
                        ".png",
                        sep=''),
           dpi = 300)
  }
}

【问题讨论】:

  • 好吧,一个向量的所有元素的索引总是会是一个向量长度的序列。但是,我想您还有其他兴趣吗?
  • 如果你想在你的循环中打印这些值,你应该print(i)而不是print(seq_along(a[[i]]))
  • 或者直接在控制台输入seq_along(a),或者print(seq_along(a))
  • 酷,谢谢@Drj 和@Renu!我知道这太简单了,很难想象.. :-D

标签: r indexing


【解决方案1】:

这是seq_along 函数的用途:

seq_along(a)
[1] 1 2 3
> cbind( seq_along(a), a)
         a  
[1,] "1" "a"
[2,] "2" "b"
[3,] "3" "c"
>  data.frame( sq = seq_along(a), a)
  sq a
1  1 a
2  2 b
3  3 c

【讨论】:

    【解决方案2】:

    如果你喜欢一些基本的东西,你可以试试:

    a<-c(5,6,7)
    b <- 1:length(a)
    

    【讨论】:

    • 虽然正确且直观,但在 for 循环迭代器中使用此范例是臭名昭著的,因为在(丢失或拼写错误)向量的长度为 0 的情况下难以理解错误。而不是返回缺少值,它返回c(1,0)
    猜你喜欢
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 2021-08-07
    • 2014-08-21
    • 2021-07-28
    相关资源
    最近更新 更多