[R] problem with function that adds rows to dataframe based on conditional statement
PIKAL Petr
petr.pikal at precheza.cz
Mon Mar 9 10:53:43 CET 2015
Hi
As you do not accept solution with adding so many NA rows for those you do not have repetitions I think that merge together with some preparation is the way to go.
First of all do not use cbind when constructing data frame
comAn=data.frame(animals,animalYears,animalMass)
# indicator variable how many repetitions in each combination animal year have
comAn$ind<-ave(comAn$animalYears, paste(comAn$animals, comAn$animalYears), FUN=table)
# expected levels (depends on how many years and repetitions for each year do you have)
lev<-expand.grid(levels(comAn$animals), 1:2, 2)
# to correct names
names(lev)[1:2]<-names(comAn)[1:2]
names(lev)[3]<-"ind"
merge(lev, comAn, all=T)
leads to put NA to the row in which required combination is missing.
You can then propagate this NA to any column you wish.
Cheers
Petr
> -----Original Message-----
> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Curtis
> Burkhalter
> Sent: Friday, March 06, 2015 10:01 PM
> To: Tom Wright
> Cc: r-help at r-project.org
> Subject: Re: [R] problem with function that adds rows to dataframe
> based on conditional statement
>
> Hey Tom,
>
> This solution works great, but if I try to then insert it in my
> function that I've displayed above and apply it to my split dataframe I
> get the error message:
>
> Error in `[.default`(xj, i) : invalid subscript type 'list'
>
> The reason why I need to try and get this to work within the function
> is that I'm trying to apply it to a much larger dataframe
> (nrow=12000,ncol=14). The actual data I'm working with consists of a
> sampling year, a site, and a bunch of response variables. For each
> sampling year by site combination I have 3 within year sampling
> occasions. For the sampling year by site combinations that don't have 3
> sampling events I need to fill in the missing occasions with the NAs.
>
> Can you see why I might be getting this error message?
>
> Thanks
>
>
>
> On Fri, Mar 6, 2015 at 1:48 PM, Tom Wright <tom at maladmin.com> wrote:
>
> > If all you want is to add a row of na's could you just do something
> > like:
> >
> > nExpectedRows<-length(unique(animals)) * length(unique(animalYears))
> *
> > 2
> >
> > newDf<-data.frame(animals=rep(NA,nExpectedRows-nrow(comAn)),
> > animalYears=rep(NA,nExpectedRows-nrow(comAn)),
> > animalMass=rep(NA,nExpectedRows-nrow(comAn)))
> >
> > comAn = rbind(comAn,newDf)
> >
> >
> >
> > On Thu, 2015-03-05 at 13:41 -0700, Curtis Burkhalter wrote:
> > > Hello everyone,
> > >
> > > I'm having a problem with a function that I wrote that is supposed
> > > to
> > add a
> > > row to dataframe based upon a conditional statement. To explain
> I've
> > > used an example below:
> > >
> > > #create data frame
> > > animals=c("bird","dog","cat")
> > > animals=rep(animals,each=4)
> > > animals=animals[1:11]
> > > animalYears=c(1,1,2,2,1,1,2,2,1,1,2)
> > > animalMass=round(runif(11,min=10,max=50),0)
> > >
> > > comAn=as.data.frame(cbind(animals,animalYears,animalMass))
> > > comAn
> > >
> > > * animals* *animalYears* *animalMass*
> > > 1 bird 1 30
> > > 2 bird 1 32
> > > 3 bird 2 27
> > > 4 bird 2 16
> > > 5 dog 1 22
> > > 6 dog 1 25
> > > 7 dog 2 41
> > > 8 dog 2 22
> > > 9 cat 1 30
> > > 10 cat 1 37
> > > 11 cat 2 49
> > >
> > > We can see here that for every type of animal I have two years of
> > > mass measurements, except for the cat in year 2. What I want to do
> > > is add an additional row to the end of the dataframe that consists
> > > strictly of NAs and then I can substitute those out later.
> > >
> > > So what I first did was split the 'comAn' dataframe into the
> > > different Animal by Year combos.
> > >
> > > #This line splits 'com_An' into a list ordered by the Animal by
> Year
> > combos
> > > comAn_split=split(comAn, paste(comAn$animals,comAn$animalYear))
> > >
> > > Then I wrote the function that identifies whether a particular
> > > Animal by Year combo is less than two rows in length and if so it
> > > should add
> > another
> > > row that consists only of NAs using the vector 'NAs':
> > >
> > > #This function identifies the length of each Animal by Year combo
> > > and
> > then
> > > #uses the rbind function built in R to add a row #to each animal by
> > > year combo if they have less than 2 samples
> > >
> > > addNA <- function(comAn) {
> > > NAs=c(NA,NA,NA)
> > > ind <- seq_len(nrow(comAn))
> > > comAn[ifelse(length(ind)<2,rbind(NAs),length(ind)),]
> > > }
> > >
> > > #This applies the function addNs to the animals data organized in
> > > list format addedNAcomAn <- do.call(rbind, lapply(comAn_split,
> > > addNA)) addedNAcomAn
> > >
> > > When I apply the function to the list of the different Animal by
> > > Year combos this is what I get:
> > > animals animalYears animalMass
> > > bird 1 bird 1 23
> > > bird 2 bird 2 50
> > > cat 1 cat 1 15
> > > cat 2 <NA> <NA> <NA>
> > > dog 1 dog 1 23
> > > dog 2 dog 2 38
> > >
> > > What I expect is this:
> > >
> > > animals animalYears animalMass
> > > 1 bird 1 41
> > > 2 bird 1 23
> > > 3 bird 2 23
> > > 4 bird 2 50
> > > 5 dog 1 49
> > > 6 dog 1 23
> > > 7 dog 2 13
> > > 8 dog 2 38
> > > 9 cat 1 42
> > > 10 cat 1 15
> > > 11 cat 2 33
> > > 12 NA NA NA
> > >
> > > Am I conditioning improperly within the function or am I missing
> > something
> > > else. Any help would be greatly appreciated.
> > >
> > > Best
> > >
> >
> >
> >
>
>
> --
> Curtis Burkhalter
>
> https://sites.google.com/site/curtisburkhalter/
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
________________________________
Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny pouze jeho adresátům.
Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze svého systému.
Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či zpožděním přenosu e-mailu.
V případě, že je tento e-mail součástí obchodního jednání:
- vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
- a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce s dodatkem či odchylkou.
- trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným dosažením shody na všech jejích náležitostech.
- odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi či osobě jím zastoupené známá.
This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.
In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.
More information about the R-help
mailing list