Hi Eik,
thank you so much - it works perfectly!
Thank you and best wishes
Alain
Eik Vettorazzi <E.Vettorazzi@uke.de> hat am 6. Februar 2013 um 17:01
geschrieben:> Hi Alain,
> here is a one-liner for a df without the rowSum column
>
>
df<-data.frame(id=c("x01","x02","x03","x04","x05","x06"),a=c(1,2,NA,4,5,6),b=c(2,4,6,8,10,NA),c=c(NA,3,9,12,NA,NA))
>
>
(df$wSum<-apply(sweep(df[,-1],1,rowSums(df[,-1],na.rm=T),"/"),1,function(x)sum(x*w,na.rm=T)))
>
> hth.
>
> Am 06.02.2013 14:17, schrieb D. Alain:
> > Dear R-List,
> >
> >
> > I am sure there must be a very simple way to do this - I just do not
know how...
> > This is what I want to do:
> >
> >
> > #my dataframe
> >
>
>
df<-data.frame(id=c("x01","x02","x03","x04","x05","x06"),a=c(1,2,NA,4,5,6),b=c(2,4,6,8,10,NA),c=c(NA,3,9,12,NA,NA),sum=c(3,9,15,24,15,6))> >
> > id a b c sum
> > 1 x01 1 2 NA 3
> > 2 x02 2 4 3 9
> > 3 x03 NA 6 9 15
> > 4 x04 4 8 12 24
> > 5 x05 5 10 NA 15
> > 6 x06 6 NA NA 6
> >
> >
> > #my weights
> > w<-c(10.5,9,12.8)
> >
>
> #now I want to calculate the proportion of the rowsum = "sum" of
every other number in the row, that is df[1,2]/df[1,5], df[1,3]/df[1,5],
...> >
> >
> > #e.g.
> >
> >
> > df.prop
> >
> >
> > id a b c sum
> > 1 x01 0.33 0.66 NA 3
> > 2 x02 0.22 0.44 0.33 9
> > 3 x03 NA 0.4 0.6 15
> > 4 x04 0.16 0.33 0.5 24
> > 5 x05 0.33 0.66 NA 15
> > 6 x06 1 NA NA 6
> >
>
> #and then calculate a rowsum, were each column is weighed by its
associated factor in the vector "w", i.e. all entries in column df$a
should be weighed by the factor 10.5, df$b by 9 and df$c by 12.8 and
then summed up to a weighed rowsum
(wrowsum=10.5*0.33+9*0.66).> >
>
> Any suggestions how to achieve this in a simple way with
dataframes that have 9000 rows and 44 columns (so I cannot do this row
by row) - sorry, if this is to easy a question.> >
> > Thank you very much in advance!
> >
> > Best wishes
> >
> > Alain
> > [[alternative HTML version deleted]]
> >
> >
> >
> > ______________________________________________
> > R-help@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.
> >
>
>
> --
> Eik Vettorazzi
>
> Department of Medical Biometry and Epidemiology
> University Medical Center Hamburg-Eppendorf
>
> Martinistr. 52
> 20246 Hamburg
>
> T ++49/40/7410-58243
> F ++49/40/7410-57790
> --
>
Pflichtangaben gemäß Gesetz über elektronische Handelsregister und
Genossenschaftsregister sowie das Unternehmensregister
(EHUG):>
> Universitätsklinikum Hamburg-Eppendorf; Körperschaft des öffentlichen
Rechts; Gerichtsstand: Hamburg
>
>
Vorstandsmitglieder: Prof. Dr. Martin Zeitz (Vorsitzender), Dr.
Alexander Kirstein, Joachim Prölß, Prof. Dr. Dr. Uwe
Koch-Gromus>
[[alternative HTML version deleted]]