Skip to content

data frame manipulation

3 messages · Pedro Mardones, arun, Jeff Newmiller

#
Hi,
Try:
dat$ID2 <- with(dat,ave(seq_along(USE),ID,FUN=function(x){x1 <- USE[x] =='001'; ifelse(!x1,'',cumsum(x1))}))
A.K.
On Thursday, February 20, 2014 3:31 PM, Pedro Mardones <mardones.p at gmail.com> wrote:
Dear R community;

I'm kind of stuck with the following situation and would appreciate any
hint. Let's assume I have the following data frame:

dat <- data.frame(ID = c(rep("01",18), rep("02",16)), USE = c(c("001","004",
"005","007","001","004","005","007","012","001","004","005","007","001","004",
"005","007","012"),c("004","005","007","013","001","004","005","007","001","004",
"005","007","001","004","005","007")),ID2 = "")

What I would like to achieve is to number all the "001" occurrences in USE
for each ID individually and store them in ID2. In other words, something
like this:

?  ID USE ID2
1? 01 001? 1
2? 01 004
3? 01 005
4? 01 007
5? 01 001?  2
6? 01 004
7? 01 005
8? 01 007
9? 01 012
10 01 001?  3
11 01 004
12 01 005
13 01 007
14 01 001?  4
15 01 004
16 01 005
17 01 007
18 01 012
19 02 004
20 02 005
21 02 007
22 02 013
23 02 001? ? 1
24 02 004
25 02 005
26 02 007
27 02 001? ? 2
28 02 004
29 02 005
30 02 007
31 02 001? ? 3
32 02 004
33 02 005
34 02 007

Thanks again,
Pedro

??? [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
#
Depending what you really want to achieve, the following may be useful or 
educational:

dat$ID2x <- with( dat, ave( rep( 1, nrow( dat ) ), ID, USE, FUN=cumsum ) )
dat$ID2y <- dat$ID2x
dat$ID2y[ dat$USE != "001" ] <- NA
On Thu, 20 Feb 2014, arun wrote:

            
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
---------------------------------------------------------------------------