-1

I have a dataset stored as a list DataList

[[1]]

[1] a  

 [2] f 

 [3] e       

 [4] a 

[[2]] 

 [1] f 

 [2] f

 [3] e

I am trying to create a function Getfrequence which return the frequence of a given pattern in the list DataList

GetFrequence<- function(pattern, DataList)
{
freq= 0
i = 1
while (i<= List.length())
 {
  if (.....)
    freq= freq + 1
 }
 return freq
}

My question is how can I search if the given pattern exists in the list?

tauculator
  • 147
  • 7
Fish
  • 131
  • 2
  • 10

1 Answers1

1

I assume that with pattern, you mean the different elements in your list. Then something like this might be helpful?

First, let us create a list roughly similar to the one you have provided above:

a <- list(letters[1:3], letters[1:2], letters[1:5])
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "a" "b"

[[3]]
[1] "a" "b" "c" "d" "e"

Now, to get the frequency of each items across the whole list, we can unlist the list and stack everything into one vector. Once we have a simple vector left, we can use table.

table(unlist(a))

 a b c d e 
 3 3 2 1 1 

Note that you may have to use unlist several times, depending on your actual list-structure. That is, if you have a list of lists, it might be necessary to adjust the code somewhat. In that case, please post str(your_list).

coffeinjunky
  • 11,254
  • 39
  • 57
  • thank you, but in reality they are not letters, they are strings (words). – Fish Mar 08 '16 at 10:13
  • How would this make a difference? Instead of the frequency of letters, you would get the frequency of the different words (i.e. the frequency of the different elements stored in the list). – coffeinjunky Mar 08 '16 at 10:14
  • Ok, Thank you. Can you explain me this line please? a <- list(letters[1:3], letters[1:2], letters[1:5]) – Fish Mar 08 '16 at 10:23
  • This is to create sample data. I have edited my answer accordingly. – coffeinjunky Mar 08 '16 at 10:29
  • If the above solves your programming problem, please consider accepting the answer so that other people can see the issue has been resolved. If your problem is not solved, please make it more concrete, for instance by providing some easy to work with sample data. See e.g. the examples provided in http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – coffeinjunky Mar 08 '16 at 10:41