简体   繁体   English

在R中的向量周围循环

[英]looping around vectors in R

I am trying to optimize the code below 我正在尝试优化下面的代码

lv1=length(new.variable1.v)
lv2=length(new.variable2.v)
lv3=length(new.variable3.v)
lv4=length(new.variable4.v)
lv5=length(new.variable5.v)

Example of values of one vector 一个向量的值的示例

new.variable1.v
 [1] 193 194 196 197 198 199 201 202 203 204 205 206 208 209 210 211

I have tried this but it doesn't work 我已经尝试过了,但是没有用

for (i in 1:5){
paste0("lv",i,"")=length(paste0(paste("new.variable", i, sep =""),".","v"))
  }

We can get the 'new.variable' in a list , get the length of each of the 'list' element with lengths . 我们可以在得到“new.variable” list ,得到了length每用“名单”元素的lengths set the names of the vector using paste , convert to a list and create new objects using list2env 使用paste设置矢量的名称,转换为list并使用list2env创建新对象

l1 <- lengths(mget(ls(pattern = "new.variable\\d+\\.v")))
l2 <- setNames(l1, paste0("lv", seq_along(l1)))
list2env(as.list(l2), envir = .GlobalEnv)

data 数据

set.seed(24)
new.variable1.v <- sample(190:220, 10, replace=FALSE)
new.variable2.v <- sample(150:180, 15, replace=FALSE)
new.variable3.v <- sample(190:220, 20, replace=FALSE)
new.variable4.v <- sample(150:180, 8, replace=FALSE)
new.variable5.v <- sample(190:220, 21, replace=FALSE)

@joran is right in the comment above. @joran在上面的注释中正确。 Save your variables into a list, like this one: 将变量保存到列表中,如下所示:

myList <- list(A = 1:3, B = 1:4, C = 1:5)

Then you can just use one of the apply functions -- here, sapply because you may want the return to be a vector. 然后,您可以仅使用apply函数之一-在这里是sapply因为您可能希望将返回值作为向量。 Use lapply if you'd rather have a list. 如果您想要一个列表,请使用lapply

sapply(myList, length)

outputs: 输出:

A B C 
3 4 5 

This works if you don't mind your vector sizes being in a list 如果您不介意向量大小在列表中,则此方法有效

vectors <- list(v1=1:5,v2=2:6)

vector_sizes <- list(v1Size=NA, v2Size=NA)

for(i in 1:length(vectors)) {
  print(vectors[i])
  vector_sizes[i] <- length(unlist(vectors[i]))
}

vector_sizes

But its not optimized, the below is much faster 但是它没有优化,下面的速度要快得多

sapply(vectors, length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM