這裏的另一種可能的解決方案:
# create your table
txt <-
"Broker_ID_Buy,Broker_ID_Sell
638,423
546,728
423,321
546,423"
dt1 <- read.csv(text=txt)
# turn "Time, Broker_ID_Buy, Broker_ID_Sell" data.frame
# into "Time, Broker_ID, Position"
buyers <- data.frame(Time=1:nrow(dt1),
Broker_ID=dt1$Broker_ID_Buy,
Position="BP",
stringsAsFactors=F)
sellers <- data.frame(Time=1:nrow(dt1),
Broker_ID=dt1$Broker_ID_Sell,
Position="SP",
stringsAsFactors=F)
longDT <- rbind(buyers,sellers)
# pivot the brocker ids on the columns
wideDT <- reshape(data=longDT,direction="wide",
timevar="Broker_ID", idvar="Time", v.names="Position")
# well-format column names and turn NAs into "IP"
names(wideDT) <- sub(x=names(wideDT),pattern="Position.","Broker_ID_")
wideDT[is.na(wideDT)] <- "IP"
結果:
> wideDT
Time Broker_ID_638 Broker_ID_546 Broker_ID_423 Broker_ID_728 Broker_ID_321
1 1 BP IP SP IP IP
2 2 IP BP IP SP IP
3 3 IP IP BP IP SP
4 4 IP BP SP IP IP
因此,同一時間(第一張表中的一行)只能有一個買入和一個賣出的經紀人,對嗎? – digEmAll 2013-03-15 17:53:18