Home > Blockchain >  Is there an R function for trimming vectors in a list to smallest vector length?
Is there an R function for trimming vectors in a list to smallest vector length?

Time:10-04

I am trying to write a function that takes a list of vectors, finds the vector with minimum length, and then makes all other vectors in the list that size.

This is what I have so far:

I first create the list of vectors,

data_list <- as.list(vector1, vector2, etc)

Then, I start writing the "trim" function to find vectors that are longer than the vector of smallest length, and reduce their length to the minimum length:

trim <- function(list){
lengths_list <- lengths(list)
min_length <- min(length_numbers)
for(i in list){
if(i > min_length){
list[i] <- list[-1:-min_length]
}
else{
next
}
}
}

When I apply this function to my list of vector, nothing happens. The lengths of the vectors do not change.

What am I doing wrong?

Thanks!

CodePudding user response:

without writing a trim function;

a <- 1:3
b <- 1:7
c <- 1:15

vec_list <- list(a,b,c)

min_length <- min(sapply(vec_list,length))

new_list <- lapply(vec_list,function(x) x[1:min_length])
                   
new_list

output;

[[1]]
[1] 1 2 3

[[2]]
[1] 1 2 3

[[3]]
[1] 1 2 3

so, we can wrap it in a function;

trim <- function(xx){
  min_length <- min(sapply(xx,length))

  new_list <- lapply(xx,function(x) x[1:min_length])

  new_list  
}

CodePudding user response:

Using @Samet Sökel data (many thanks!), we could do a lapply and find the minimum length of all lists:

lapply(vec_list, function(i)i[seq(min(lengths(vec_list)))])
[[1]]
[1] 1 2 3

[[2]]
[1] 1 2 3

[[3]]
[1] 1 2 3
  • Related