-1

I have a dataframe with 213 rows indicating quarters. Here just a chunck:

quart <- c("2000 Q1", "2000 Q1", "2000 Q1", "2000 Q1", "2000 Q2", "2000 Q2", "2000 Q2", "2000 Q3", "2000 Q3", "2000 Q4", "2000 Q4", "2000 Q4", "2000 Q4", "2001 Q1", "2001 Q1", "2001 Q2", "2001 Q2", "2001 Q2", "2001 Q2")

df <- data.frame(quart)

   quart
1  2000 Q1
2  2000 Q1
3  2000 Q1
4  2000 Q1
5  2000 Q2
6  2000 Q2
7  2000 Q2
8  2000 Q3
9  2000 Q3
10 2000 Q4
11 2000 Q4
12 2000 Q4
13 2000 Q4
14 2001 Q1
15 2001 Q1
16 2001 Q2
17 2001 Q2
18 2001 Q2
19 2001 Q2

I would like to take just the first element of each new quarter. To make it clear:

   quart

1  2000 Q1
2  2000 Q2
3  2000 Q3
4 2000 Q4
5 2001 Q1
6 2001 Q2

Can anyone help me?

Thanks!

Rollo99
  • 1,601
  • 7
  • 15

3 Answers3

1

One very simple method might be to simply use unique():

quart <- c("2000 Q1", "2000 Q1", "2000 Q1", "2000 Q1", "2000 Q2", "2000 Q2", "2000 Q2", "2000 Q3", "2000 Q3", "2000 Q4", "2000 Q4", "2000 Q4", "2000 Q4", "2001 Q1", "2001 Q1", "2001 Q2", "2001 Q2", "2001 Q2", "2001 Q2")

df <- data.frame(quart)

df2 <- unique(df)
Kris
  • 420
  • 2
  • 11
  • 2
    This doesn't scale up if there are more columns. – jay.sf Oct 21 '19 at 14:10
  • 1
    That's a good point, @jay.sf. OP, if this is only one column of a data frame, my solution will *only* return that column. Please clarify if your data is larger than this one column. – Kris Oct 21 '19 at 14:15
  • 1
    For future readers, I am signing this as a correct answer as it is the quickest way to get the result I want. Yet, note that this works only for one column data-frames as it was pointed out. All other answers work perfectly on dataframes with more than one column. Thank you all! – Rollo99 Oct 21 '19 at 14:19
1

You can use slice() on a grouped data frame via dplyr

library(dplyr)
df %>% 
  arrange(quart) %>% 
  group_by(quart) %>% 
  slice(1)
mnist
  • 6,571
  • 1
  • 18
  • 41
1

you could just ask for values that are not duplicated.

Want <- subset(have, !duplicated(have[,"quart"]))
Schilker
  • 505
  • 2
  • 11