Skip to content

beginner question: subset first entry (row) per week

3 messages · Bert Gunter, Dagmar

#
Dear knowing people,

I have a data frame like this.

exdatframe <- data.frame(Name=c("Ernie","Ernie","Ernie", 
"CookieMonster","CookieMonster","CookieMonster"),
recordedTime=as.POSIXct(strptime(as.character("01.01.2017","02.01.2011","03.01.2011",
"01.01.2011","02.01.2011","03.01.2011"),"%d.%m.%Y")),
                          week =c(1,2,2,
                                 1,2,2),
                          eatencookies=c(1,0.5,0.001,
                                        50,51,200))
exdatframe

#Now I want a new dataframe with only the first row per week (i.e. I 
want to know how many cookies were eaten at the first recorded day of 
each week). Something like that:

exdatframe2 <- data.frame(Name=c("Ernie","Ernie", 
"CookieMonster","CookieMonster"),
                          recordedTime=c("01.01.2017","02.01.2011",
"01.01.2011","02.01.2011"),
                          week =c(1,2,
                                  1,2),
                          eatencookies=c(1,0.5,
                                         50,51))
exdatframe2

# How do I do that? I thought it must be something with tapply or subset 
- but I just don't get it....

# would be great if someone helps.

# Dagmar
#
new.df <- orig.df[!duplicated(df[["week"]]), ]

See ?duplicated

-- Bert
Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Thu, Feb 2, 2017 at 1:04 PM, Dagmar <Ramgad82 at gmx.net> wrote:
#
Dear all,

Now, all the sudden I found the answer myself :-)

I did it by:

ddply(exdatframe,.(week),function(x) head(x,1))

I'll simply do it for Ernie and Cookiemonster seperate - that is not a 
big problem.

Thanks anyway for your engagement in this group!

Dagmar


Am 02.02.2017 um 22:04 schrieb Dagmar: