[R] Summing over specific columns in a matrix

Mark Knecht markknecht at gmail.com
Fri Jan 7 19:21:22 CET 2011


On Fri, Jan 7, 2011 at 8:42 AM, Henrique Dallazuanna <wwwhsd at gmail.com> wrote:
> Try this:
>
> rowSums(rowsum(t(m), rep(1:3, c(2, 2, 1)), na.rm = TRUE))
>
>
> On Fri, Jan 7, 2011 at 2:29 PM, emj83 <stp08emj at shef.ac.uk> wrote:
>
>>
>> Hi,
>>
>> I would like to sum some specific columns in my matrix- for example, my
>> matrix looks like this:
>>     [,1]  [,2]  [,3] [,4]  [,5]
>> [1,]    1   NA   NA   NA   NA
>> [2,]    2    1   NA    1   NA
>> [3,]    3    2    1     2    1
>> [4,]    4    3    2     3    2
>> [5,]   NA   NA   NA    4    3
>> [6,]   NA   NA   NA    5   NA
>>
>> I would like to find the sum of the first two columns, the second two
>> columns and the last column:
>> i.e I am left with a vector of c(16, 18, 6).

Can you help me extend this example?

I'd like to get (PL_Pos - Costs) for each row in Data1, sum those
results for each matching date in Result1, and put the result in a new
column in Result1 called 'Daily'.

Been messing with this for an hour now. Nothing comes close.

Thanks,
Mark


Result1 = structure(list(TradeDates = structure(c(14249, 14250, 14251,
14252, 14253, 14256, 14257, 14258, 14259, 14260, 14263, 14264
), class = "Date")), .Names = "TradeDates", row.names = c(NA,
12L), class = "data.frame")

Data1 = structure(list(Trade = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22), PosType = c(1, 1, -1,
-1, -1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1,
1, -1), EnDate = structure(c(14249, 14250, 14251, 14253, 14256,
14256, 14256, 14257, 14258, 14258, 14259, 14259, 14260, 14264,
14264, 14265, 14266, 14267, 14270, 14271, 14273, 14274), class = "Date"),
    EnTime = c(1406, 1318, 838, 846, 846, 1038, 1102, 918, 838,
    950, 1134, 1254, 1110, 846, 1318, 854, 950, 838, 1246, 838,
    854, 902), ExDate = structure(c(14249, 14250, 14251, 14253,
    14256, 14256, 14256, 14257, 14258, 14258, 14259, 14259, 14260,
    14264, 14264, 14265, 14266, 14267, 14270, 14271, 14273, 14274
    ), class = "Date"), ExTime = c(1515, 1515, 1030, 942, 1030,
    1046, 1110, 1515, 942, 1030, 1142, 1515, 1515, 1030, 1326,
    1515, 1515, 1030, 1515, 1515, 1515, 1022), PL_Pos = c(133.5,
    -41.5, 171, 483.5, 333.5, -29, -54, -291.5, 596, -141.5,
    -54, 558.5, 533.5, 521, -41.5, 883.5, 358.5, -979, -191.5,
    196, -791.5, 446), Costs = c(29, 29, 29, 29, 29, 29, 29,
    29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
    ), PL = c(104.5, -70.5, 142, 454.5, 304.5, -58, -83, -320.5,
    567, -170.5, -83, 529.5, 504.5, 492, -70.5, 854.5, 329.5,
    -1008, -220.5, 167, -820.5, 417)), .Names = c("Trade", "PosType",
"EnDate", "EnTime", "ExDate", "ExTime", "PL_Pos", "Costs", "PL"
), row.names = c(NA, 22L), class = "data.frame")

Result1
Data1



More information about the R-help mailing list