hey ppl, i am new to r language.. so i just want to know how array indexing is done in r language , i mean like sorting or any calcultaions that involve 2-d arrays.
well, i was writing a code where i had to perform a calculation like this a[i]=(-12*(a[i]+a[i+1])+3*(a[i+2]+a[i+3])+14*a[i+4])/35now this showed me an error:Error in Ops.data.frame(a[i], a[i + 4]) : + only defined for equally-sized data framesi am unable to understand what kind of error it is..!!!although i tried various possibilities i am unsuccessful so guys please help me out..!!
Abhinavvv
2010-06-21 16:14:40
It depends on what `a` is. If it is a dataframe then a[2] means the second column. If you need a single element you have to give both row and column indices, e.g. a[1,2]. If you want, say, the third row, you'll have to give a[3,]
gd047
2010-06-21 17:38:04
+1
A:
It depends,
To index elements use square brackets: ar[1]
, or ar[1,1]
for 2d.
Whole columns and rows are: ar[,1]
or ar[1,]
For sorting, look at the sort
and order
functions.
For calculations using 2d arrays, you can have:
Elementwise: ar1+ar2
, ar1*ar2
Inner product: ar1%*%ar2
Outer product: outer(ar1,ar2)
or ar1%o%ar2
You must take care that the dimensions of the arrays are correct for what you want to do, though R will automatically try to recycle elements to complete a calculation.
One thing to note is that indexing is 1-based, not 0-based as in most languages, ie the first element is ar[1]
.
James
2010-06-21 10:47:52
well, i was writing a code where i had to perform a calculation like this a[i]=(-12*(a[i]+a[i+1])+3*(a[i+2]+a[i+3])+14*a[i+4])/35 now this showed me an error: Error in Ops.data.frame(a[i], a[i + 4]) : + only defined for equally-sized data frames i am unable to understand what kind of error it is..!!! although i tried various possibilities i am unsuccessful so guys please help me out..!! –
Abhinavvv
2010-06-21 16:55:21
Well it seems that a is a dataframe, so you might want to coerce it to a matrix (`as.matrix(a)`), or extract a vector (by referencing a whole row or column as above). Depends whats in it really.
James
2010-06-22 09:03:37