user4797853 user4797853 - 1 month ago 6
R Question

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"))
}

Answer

We can get the 'new.variable' in a list, get the length of each of the 'list' element with lengths. set the names of the vector using paste, convert to a list and create new objects using 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)