简体   繁体   中英

Reshape a data frame in R

I have a data frame that looks like

F1      F2        Number
Banana  Apple     9
Orange  Banana    7
Apple   Orange    8
Banana  Orange    6

I need to convert this to

Type    F1   F2
Banana  15   7
Orange  7    14
Apple   8    9

Here's an approach:

setNames(merge(aggregate(Number ~ F1, dat, sum),
               aggregate(Number ~ F2, dat, sum),
               by.x = "F1", by.y = "F2", all = TRUE),
         c("Type", "F1", "F2"))

#     Type F1 F2
# 1  Apple  8  9
# 2 Banana 15  7
# 3 Orange  7 14

where dat is the name of your data frame.

This problem can also be tackled pretty easily with the "reshape2" package:

library(reshape2)

x <- melt(mydf, id.vars="Number")
dcast(x, value ~ variable, value.var="Number", fun.aggregate=sum)
#    value F1 F2
# 1  Apple  8  9
# 2 Banana 15  7
# 3 Orange  7 14

However, it is also pretty easily tackled with base R:

xtabs(Number ~ values + ind, 
      cbind(mydf["Number"], 
            stack(mydf[setdiff(names(mydf), "Number")])))
#         ind
# values   F1 F2
#   Apple   8  9
#   Banana 15  7
#   Orange  7 14

In cases where your data are already long, as they are in your comment , it is even more straightforward:

xtabs(Number ~ Date + Type, mydf)
#           Type
# Date       M1 M2
#   01/01/14  9  7
#   01/02/14  8  6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM