0

I am downloading data from Bloomberg and then update it in R. The dataframe looks as follows.

 ticker       date PX_LAST PE_RATIO
1 SMI Index 2014-09-30 8835.14  20.3692
2 SMI Index 2014-10-31 8837.78  20.3753
3 DAX Index 2014-09-30 9474.30  16.6487
4 DAX Index 2014-10-31 9326.87  16.3896
5 SMI Index 2014-11-28 9150.46  21.0962
6 SMI Index 2014-12-31 8983.37  20.6990
7 DAX Index 2014-11-28 9980.85  17.5388
8 DAX Index 2014-12-31 9805.55  16.8639

Now I would like to have this dataframe sorted according to ticker (not in alphabetical order, but in the order of the ticker) and then the date so that the end result would be:

 ticker       date PX_LAST PE_RATIO
1 SMI Index 2014-09-30 8835.14  20.3692
2 SMI Index 2014-10-31 8837.78  20.3753
3 SMI Index 2014-11-28 9150.46  21.0962
4 SMI Index 2014-12-31 8983.37  20.6990
5 DAX Index 2014-09-30 9474.30  16.6487
6 DAX Index 2014-10-31 9326.87  16.3896
7 DAX Index 2014-11-28 9980.85  17.5388
8 DAX Index 2014-12-31 9805.55  16.8639

2 Answers 2

3

There's a function chgroup() in the data.table package that does exactly what you're looking for. It groups values from the vector together while preserving the initial order. It is only available for character vectors (ch for character).

require(data.table)
DF[chgroup(DF$ticker), ]
#     ticker       date PX_LAST PE_RATIO
# 1 SMIIndex 2014-09-30 8835.14  20.3692
# 2 SMIIndex 2014-10-31 8837.78  20.3753
# 5 SMIIndex 2014-11-28 9150.46  21.0962
# 6 SMIIndex 2014-12-31 8983.37  20.6990
# 3 DAXIndex 2014-09-30 9474.30  16.6487
# 4 DAXIndex 2014-10-31 9326.87  16.3896
# 7 DAXIndex 2014-11-28 9980.85  17.5388
# 8 DAXIndex 2014-12-31 9805.55  16.8639

If your ticker column is factor, then convert it first to character type.

Sign up to request clarification or add additional context in comments.

Comments

2

You could try order

 df$ticker <- factor(df$ticker, levels=unique(df$ticker))
 df1 <- df[with(df, order(ticker, date)),]
 row.names(df1) <- NULL
 df1
 #     ticker       date PX_LAST PE_RATIO
 #1 SMI Index 2014-09-30 8835.14  20.3692
 #2 SMI Index 2014-10-31 8837.78  20.3753
 #3 SMI Index 2014-11-28 9150.46  21.0962
 #4 SMI Index 2014-12-31 8983.37  20.6990
 #5 DAX Index 2014-09-30 9474.30  16.6487
 #6 DAX Index 2014-10-31 9326.87  16.3896
 #7 DAX Index 2014-11-28 9980.85  17.5388
 #8 DAX Index 2014-12-31 9805.55  16.8639

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.