0

I need to group data in a table structured like a:

    # origin  type amount
    1      1    t1    100
    2      1    t2    100
    3      1    t3    100
    4      2    t1    100
    5      2    t2    100
    6      1    t1    100

to get a table like a:

    #    t1  t2  t3
    1   200 100 100
    2   100 100  NA

Dimensions of a new table come from the value of columns "origin" and "type". Sum of same-type values and NA indicates that the function should process other than one occurrences of a particular type.

Is there any single command to achieve that? If not what the chain of commands could be? Thanks.

Jaap
  • 81,064
  • 34
  • 182
  • 193
cineS.
  • 93
  • 1
  • 7

1 Answers1

0

Many methods are there, but easiest base R option is

xtabs(amount~origin + type, df1)

Or with tapply

with(df1, tapply(amount, list(origin, type), FUN = sum))
#   t1  t2  t3
#1 200 100 100
#2 100 100  NA
akrun
  • 874,273
  • 37
  • 540
  • 662