R:获取向量中所有元素的索引? [英] R: Get indices of all elements in a vector?
问题描述
简单的问题,但我找不到答案.
Simple questions, but I can't find an answer.
我有一个向量
a<-c(5,6,7)
如何获取向量中所有元素的索引?
how can I get back the indices for all elements in my vector?
我需要回来
1 #"a"
2 #"b"
3 #"c"
或 c(1,2,3)
如果我运行seq_along(a),它会返回(1,1,1)
而不是(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
原因是我需要为每个图创建一个唯一的名称.我有大约100个图,说明了100个位置.位置名称太长且包含特殊字符,因此我无法使用它们来命名输出图.我想使用索引值来代替每个已保存图的名称.
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.
我需要修改的功能:
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)
}
}
推荐答案
这是 seq_along
函数所服务的目的:
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
这篇关于R:获取向量中所有元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!