list - Function for same length of vectors in R -


i want make function, should remake list of vectors of different lengths list of vectors same lengths. made 2 functions, second 1 not work well. code is: first function (works well)

delka<-function(x){   delky<<-null   for(i in 1:length(x)){     delky[i]<<-length(x[[i]])   } } 

here globally made object "delky". second function is

uprava<- function(x){   stejne<<- null   for(i in 1:length(x)){     stejne[[i]]<<-vector(x[[i]], length(max(delky)))   } }     

where want globally make object "stejne" containing vectors same lengths. r answer me issue

error in vector(x[[i]], length(max(delky))) : invalid 'mode' argument

do have ideas of doing wrong?

assuming can work on whole lists @ time, , if want pad shorter vectors nas, here's 1 way.

my <- list(a = runif(5),            b = runif(11),            c = runif(7))  maxl <- max(sapply(my, length))  sapply(my, fun = function(x, ml) {   difference <- ml - length(x)   c(x, rep(na, difference)) }, ml = maxl, simplify = false)  $a  [1] 0.91906470 0.68651070 0.07317576 0.52985130 0.27916889         na         na         na         na         na         na  $b  [1] 0.86384953 0.79707167 0.88226627 0.91590091 0.03181455 0.86493584 0.89597354 0.80890065 0.92418156 0.72947596 0.13847751  $c  [1] 0.2576621 0.6512487 0.5806530 0.8782730 0.0262019 0.1000885 0.5245472        na        na        na        na 

in representation

sapply(my, fun = function(x, ml) {   difference <- ml - length(x)   c(x, rep(na, difference)) }, ml = maxl)                          b         c  [1,] 0.91906470 0.86384953 0.2576621  [2,] 0.68651070 0.79707167 0.6512487  [3,] 0.07317576 0.88226627 0.5806530  [4,] 0.52985130 0.91590091 0.8782730  [5,] 0.27916889 0.03181455 0.0262019  [6,]         na 0.86493584 0.1000885  [7,]         na 0.89597354 0.5245472  [8,]         na 0.80890065        na  [9,]         na 0.92418156        na [10,]         na 0.72947596        na [11,]         na 0.13847751        na 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -