0

I am working with a data set that has a column which I have turned into a list that looks like this:

[[997]]
[1] NA

[[998]]
[1] "0.99"  " 0.99" " 0.99" " 0.99" " 0.99" " 2.99"

[[999]]
[1] "19.99"  " 9.99"  " 4.99"  " 79.99" " 15.99" " 14.99" " 99.99" " 7.99" 
[9] " 59.99" " 49.99"

[[1000]]
[1] NA

I need to count how many components are in each element of a list and save these values in a matrix. For example, in 999 the output should be 10 and in 1000 the output should be 0. Can anyone suggest a function that could help? Thank you.

zx8754
  • 52,746
  • 12
  • 114
  • 209
H. Minear
  • 87
  • 1
  • 8
  • BTW, your title does not reflect your question. You are not counting for character, you want to count for number of elements in a list. – dc37 Dec 01 '19 at 21:03

2 Answers2

3

Here, using a small example of list v:

v = vector("list",4)
v[[1]] = 1:5
v[[2]] = 1:50
v[[3]] = NA

> v
[[1]]
[1] 1 2 3 4 5

[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
[37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50

[[3]]
[1] NA

[[4]]
NULL

And you get the count by doing:

l = unlist(lapply(v,length))

and

> l
[1]  5 50  1  0

If you don't want to count for NA

l = unlist(lapply(v,function(x)length(x[!is.na(x)])))

and you get:

> l
[1]  5 50  0  0

EDIT: from @markus and @A5C1D2H2I1M1N2O1R2T1 comments

As mentioned by @markus, you can go much much simpler by doing:

> lengths(v)
[1]  5 50  1  0

And as mentioned by @A5C1D2H2I1M1N2O1R2T1, you can get rid of NA count by doing:

> replace(lengths(v), is.na(v), 0)
[1]  5 50  0  0
dc37
  • 15,840
  • 4
  • 15
  • 32
2

Additional to the existing solution by @dc37, you can also use the following with lengths()

lengths(v)

If you don't want to take NA into account, then try

lengths(v)*!is.na(v)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81