Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count new elements in vector list

Tags:

r

lapply

I want to count new elements that weren't present in previous years. In the example

Sample data:

var1 <- list('2003' = 1:3, '2004' = c(4:3), '2005' = c(6,4,1), '2006' = 1:4 )

I would like to get the output

newcount <- list('2003' = 0, '2004' = 1, '2005' = 1, '2006' = 0)

Unsuccessful code:

newcount <- mapply(setdiff, var1, seq_along(var1), function(i) 
            {if (i > 1) {Reduce(union, var1[i-1], accumulate=T)}}, length)
like image 818
dmvianna Avatar asked Sep 04 '12 07:09

dmvianna


People also ask

How do you count elements in vectors?

The built-in function exists in C++ to count the size of the vector. The function name is, size(). It returns the size or the total elements of the vector in which vector it is used.

Can we use count function in vector?

C++ STL std:count() functionYou can use this function with an array, string, vector, etc. To use this function, we have to use either <bits/stdc++> header or <algorithm> header. Syntax of std::count() function: count( start_point , end_point , val/element);


1 Answers

Almost there, but its better to use vector indexing to work with the offset and add the always-known initial element afterwards:

lapply(c(list(`2003`=integer(0)),
       mapply(setdiff,var1[-1], 
              Reduce(union,var1,accumulate=TRUE)[-length(var1)])),length)
$`2003`
[1] 0

$`2004`
[1] 1

$`2005`
[1] 1

$`2006`
[1] 0
like image 90
James Avatar answered Oct 24 '22 18:10

James