How to remove empty level form a vector in R

r
loopfunction

#1

I am working on split function and I have created two level using gl function and then I have use interaction function on it agter creating split function I have use str function on it and I am getting some num(0) value I want to remove them

x<-rnorm(10)
f1<-gl(2,5)
f2<-gl(5,2)
y<-interaction(f1,f2)
str(split(x,y))
List of 10
1.1: num [1:2] 0.287 1.42 2.1: num(0)
1.2: num [1:2] 0.472 -0.956 2.2: num(0)
1.3: num 0.619 2.3: num -0.296
1.4: num(0) 2.4: num [1:2] -0.496 -1.055
1.5: num(0) 2.5: num [1:2] 1.053 0.322


#2

First, it is not a vector, it’s a list. You can use the Filter function as follows:

z<- split(x,y)
Filter(length,z)

gives the required output as:

$1.1
[1] 0.14538513 0.08451867

$1.2
[1] 0.3082437 -0.6722462

$1.3
[1] -0.1701237

$2.3
[1] -0.2955505

$2.4
[1] -0.4849099 -0.6544547

$2.5
[1] 0.6218630 0.795897

Alternatively,
you may use the lapply function to first find the elements that have positive length and then subset them from the list as follows:

z[lapply(z,length)>0]

Hope this helps!