How to create a table with two-factorial data

288 Views Asked by At

is there a possibility to show data that is two-factorial in a table using R?

Please consider my example with replicates.

So one has two or more values in every cell.

I tried using ftable() and table() but am not getting anywhere :(

Thank you so much for helping

Example input

A    B    Value
1    1    1.2
1    1    1.4
1    2    2.1
1    2    2.0
2    1    1.1
2    1    1.2
2    2    3.1
2    2    3.1

Desired output, something like enter image description here

2

There are 2 best solutions below

2
On BEST ANSWER

Perhaps something like the following would be helpful:

library(data.table)
library(reshape2)
dcast.data.table(
  as.data.table(df)[, `:=`(A = paste0("A", A),   ## Prefix A values with "A"
                           B = paste0("B", B))], ## Prefix B values with "B"
  A ~ B, value.var = "Value",                    ## Our casting formula
  fun.aggregate = function(x)                    ## Our aggregation formula
    paste(sprintf("%2.2f", x), collapse = "/"))  ## sprintf -> uniform format
#     A        B1        B2
# 1: A1 1.20/1.40 2.10/2.00
# 2: A2 1.10/1.20 3.10/3.10

I've added comments in the code to explain what's going on at each step.

0
On

The tapply function is the standard base-R mechanism for getting afunction to be applied to a cross-classified value:

tapply(dat$Value, list(A=dat$A,B=dat$B) , function(x) paste(x,collapse="/"))
#----------
   B
A   1         2        
  1 "1.2/1.4" "2.1/2"  
  2 "1.1/1.2" "3.1/3.1"

If you wanted annotation:

tapply(dat$Value, list(A=dat$A,B=dat$B) , function(x) paste("V1=",x[1],"V2=",x[2]))
#--------------
   B
A   1                 2                
  1 "V1= 1.2 V2= 1.4" "V1= 2.1 V2= 2"  
  2 "V1= 1.1 V2= 1.2" "V1= 3.1 V2= 3.1"