R: Get indices of all elements in a vector?

南笙酒味 提交于 2021-02-05 12:37:59

问题


Simple questions, but I can't find an answer.

I have a vector

a<-c(5,6,7)

how can I get back the indices for all elements in my vector?

I need back

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

or c(1,2,3)

If I run seq_along(a), it gives me back (1,1,1) not (1,2,3):

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

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

The reason for this is that I need to create a unique name for each of my plots. I have about 100 plots illustrating 100 locations. Locations'names are too long and contain special characters, thus I can't use them to name my output plots. I would like to use the index value to substitute the name for each saved plot.

My function that I need to modify:

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)
  }
}

回答1:


This is the purpose served by the seq_along function:

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:


If you like something elementary, you can try:

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


来源:https://stackoverflow.com/questions/49438348/r-get-indices-of-all-elements-in-a-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!