[R] Code to construct table with paired data

peter dalgaard pdalgd at gmail.com
Sat Apr 8 14:11:01 CEST 2017


Here's one way:

> ddw <- reshape(dd, direction="wide", idvar="pair", timevar="treatfac")
> names(ddw)
[1] "pair"      "imprfac.A" "imprfac.B"
> xtabs(~ imprfac.A + imprfac.B, ddw)
         imprfac.B
imprfac.A + -
        + 1 3
        - 2 1

(reshape() is a bit of a pain to wrap one's mind around; possibly, the tidyversalists can come up with something easier.)

With a bit stronger assumptions on the data set (all pairs complete and in same order for both treatments), there is also

> table(A=imprfac[treatfac=="A"], B=imprfac[treatfac=="B"])
   B
A   + -
  + 1 3
  - 2 1



> On 08 Apr 2017, at 13:16 , Mauricio Cardeal <mcardeal at ufba.br> wrote:
> 
> Hi!
> 
> Is it possible to automatically construct a table like this:
> 
> #                        treat B
> #                       improvement
> #                         +       -
> #treat A improvement  +   1       3
> #                     -   2       1
> 
> From these data:
> 
> pair  <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7)  # identification
> treat <- c(1,0,1,0,1,0,1,0,1,0,1,0,1,0) # treatament 1 (A) or 0 (B)
> impr  <- c(1,0,1,0,1,0,0,1,0,1,0,0,1,1) # improvement 1 (yes) 0 (no)
> 
> treatfac <- factor(treat)
> levels(treatfac)<-list("A"=1,"B"=0 )
> imprfac <- factor(impr)
> levels(imprfac)<-list("+"=1,"-"=0)
> 
> data.frame(pair,treatfac,imprfac)
> 
>    pair treatfac imprfac
> 
> 1     1      A     +
> 2     1      B     -
> 3     2      A     +
> 4     2      B     -
> 5     3      A     +
> 6     3      B     -
> 7     4      A     -
> 8     4      B     +
> 9     5      A     -
> 10    5      B     +
> 11    6      A     -
> 12    6      B     -
> 13    7      A     +
> 14    7      B     +
> 
> I tried some functions like table or even xtabs, but the results doesn't 
> show the pairs combinations.
> 
> 
> Thanks in advance,
> 
> 
> Maurício Cardeal
> 
> Federal University of Bahia, Brazil
> 
> 
> 
> 
> 	[[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.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list