【发布时间】: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