在R中如何创建和追加'命名'向量。我目前的方法是创建单独的名称向量并稍后指定名称。
v = c()
vName = c()
for (i in 1:5) {
# do something complicated and store output
k = i*i ## or get output from any other function
v = c(v,k)
vName = c(vName, k)
}
names(v) = vName
有更好的方法吗?
答案 0 :(得分:4)
在某些简单情况下,您可以使用setNames
:
setNames(1:5, letters[1:5])
但在循环之外应用名称是一个很好的方法。如果预先分配向量,则可以在循环中添加名称:
# pre-allocate vectors of known size (length of for loop)
v=numeric(5)
vName = character(5)
for (i in 1:5) {
# do something complicated and store output
k = i*i ## or get output from any other function
kName = <something related to k>
v[i] = k
vName[i] = kName
}
预先分配向量,在内存中设置一个固定的点,在循环中填充。如果你反复追加它们,R必须在每次迭代中复制矢量。
答案 1 :(得分:1)
可以在循环中附加名称的另一种方法是使用names():
# Create empty vector of known size
v <- vector(mode = "numeric", length = 5)
# Fill the named vector with the loop
for (i in 1:5) {
k <- i*i
kName <- paste0("name", i) # generates "name1", "name2", etc
v[i] <- k # adds element to vector
names(v)[i] <- kName # adds name to the current element
}