0

I have a vector of data called empl which I extracted from a NetLogo model using RNetLogo and whose entries look like

[[1403]]
[1] 99

[[1404]]
[1] 97

[[1405]]
[1] 95

[[1406]]
[1] 95

[[1407]]
[1] 95

[[1408]]
[1] 97

I would like to perform simple operation on the last numbers of the vector's entries (the 95,97,...).

Now if I write something like

empl[731] + empl[890]

I get

Error in empl[i] + empl[j] : non-numeric argument to binary operator

If I understand correctly, this is due the fact that empl[i] does not pick the last number in the corresponding entry but rather the whole entry for instance

[[1408]]
    [1] 97

But I haven't been able to figure out how to get the last number only. I tried

empl[1,i]

and

empl[i,1]

but got

Error in empl[1, i] : incorrect number of dimensions

Any help on how to select the last number only would be much appreciated. If someone can emply understand the structure of the vector empl that would be even better.

  • 1
    Might seem a little odd to flag my own question as possible duplicate, but I found the possible duplicate only after asking the question. I wanted to delete my own question, but got a warning message indicating it was not good practice. I guess it is better to leave the community decide whether it is worth keeping the two questions. – Martin Van der Linden Dec 24 '14 at 11:11

2 Answers2

2

Your empl object is not a vector. It is a list. A list object is formed by elements which can be arbitrary R objects. When you print a list and see:

    [[1403]]
    [1] 99

it means that the 1403rd element of this list is a vector with just one value (99). You select an element of a list through the double square bracket ([[) operator. So, if you try:

    empl[[731]] + empl[[890]]

you won't receive any error. I suggest to read the R language definition, and in particular sections 2.1 (which describes object types) and 3.4 (when indexing is discussed).

nicola
  • 24,005
  • 3
  • 35
  • 56
  • Thanks very clear and helpful. Thanks for the link too. Somehow I got tricked by the fact that is.vector(empl) reports TRUE, but should have dig a little deeper, e.g. http://stackoverflow.com/questions/11597175/why-the-object-is-vector. – Martin Van der Linden Nov 07 '14 at 15:00
1

It seems like empl is a list

You could do

Reduce(`+`,tail(empl,2))

to get the sum of last 2 elements

If you need to sum some specific elements for example 731, 752, 834

 Reduce(`+`,empl[c(731, 752, 834)])
 #[1] 812

Or

sum(unlist(tail(empl,2)), na.rm=TRUE)

data

set.seed(42)
empl <- replicate(1000,list(sample(1:950,1,replace=TRUE)))
akrun
  • 874,273
  • 37
  • 540
  • 662