Reputation:
Since most of the words I search return an empty list, I'd like to keep only those which give a result.
> assocs<-findAssocs(dtm,names(freq[1:5]),0.5)
> assocs
$cuffie
numeric(0)
$auricolari
colora controlli interrotta operazione verrà
0.52 0.52 0.51 0.51 0.50
$qualità
numeric(0)
$suono
numeric(0)
$ricarica
colora interrotta operazione verrà addentrarmi attira
0.57 0.56 0.55 0.54 0.53 0.53
attirano avanzati consigliarveli consultato iniziare interromperne
0.53 0.53 0.53 0.53 0.53 0.53
inutilmente mettersi negativamente reinserire ritornare siribixbygoogle
0.53 0.53 0.53 0.53 0.53 0.53
specifico ventina collocare
0.53 0.53 0.52
Desired Output:
> assocs
$auricolari
colora controlli interrotta operazione verrà
0.52 0.52 0.51 0.51 0.50
$ricarica
colora interrotta operazione verrà addentrarmi attira
0.57 0.56 0.55 0.54 0.53 0.53
attirano avanzati consigliarveli consultato iniziare interromperne
0.53 0.53 0.53 0.53 0.53 0.53
inutilmente mettersi negativamente reinserire ritornare siribixbygoogle
0.53 0.53 0.53 0.53 0.53 0.53
specifico ventina collocare
0.53 0.53 0.52
By doing so I could search on more words without having returned an enormous list.
The library used for findassocs() is tm.
The output is:
> class(assocs)
[1] "list"
I have tried this:
for (i in 1:5){
if (length(assocs[[i]])==0){
new_assocs[j]=assocs[i]
j=j+1
}
}
But the output was like this:
> new_assocs
[[1]]
numeric(0)
[[2]]
numeric(0)
[[3]]
numeric(0)
[[4]]
numeric(0)
[[5]]
numeric(0)
Thank you all in advance.
Upvotes: 1
Views: 578
Reputation: 15907
The function lengths()
returns the number of elements (i.e., the length) for each element in a list. So you can do this:
assocs[lengths(assocs) >= 1]
This is, of course, basically the same answer as Daniel O's, but it is somewhat simpler and, for large lists, more efficient.
Upvotes: 1
Reputation: 4358
You can check the length since numeric(0)
has no length
assocs[sapply(assocs, function(x) length(x) >= 1)]
Upvotes: 2