简单的问题,但我找不到答案。
我有一个向量
a<-c(5,6,7)
Run Code Online (Sandbox Code Playgroud)
如何取回向量中所有元素的索引?
我需要回来
1 #"a"
2 #"b"
3 #"c"
Run Code Online (Sandbox Code Playgroud)
或者 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
Run Code Online (Sandbox Code Playgroud)
这样做的原因是我需要为我的每个图创建一个唯一的名称。我有大约 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)
}
}
Run Code Online (Sandbox Code Playgroud)
这是该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
Run Code Online (Sandbox Code Playgroud)