嵌套的xtab表

时间:2018-01-30 17:25:03

标签: r

我想为多级析因实验生成嵌套表。我检查了10种油漆的时间,以达到4个湿度,3个温度和2个风速下的终点。当然我在网上搜索但没有成功。

可以使用以下方法生成一些示例代码:

##  Made  Up  Data  # NB the data is continuous whereas observations were made 40/168 so data is censored.
 time3 <- 4*seq(1:24)   # Dependent: times in hrs, runif is not really representative but will do
 wind  <- c(1,2)        # Independent: factor draught on or off
 RH    <- c(0,35,75,95) # Independent: value for RH but can be processes as a factor
 temp  <- c(5,11,20)    # Independent: value for temperature but can be processed as a factor
 paint <- c("paintA", "paintB", "paintC")   # Independent: Experimental material
# Combine into dataframe 
 dfa       <- data.frame(rep(temp,8))
 dfa$RH    <- rep(RH,6)
 dfa$wind  <- rep(wind,12)
 dfa$time3 <- time3
 dfa$paint <- rep(paint[1],24)
# Replicate for different paints
 dfb       <-  dfa
 dfb$paint <-  paint[2]  
 dfc       <-  dfa
 dfc$paint <-  paint[3]
 dfx       <-  do.call("rbind", list(dfa,dfb,dfc))
# Rename first col 
 colnames(dfx)[1] <- "temp" 
# Prepare xtab tables
 tx <- xtabs(dfx$time3 ~ dfx$wind + dfx$RH + dfx$temp + dfx$paint)
 tx

我希望获得的目标就像这样xtab example

tx <- xtabs(dfx$time3 ~ dfx$wind + dfx$RH + dfx$temp) 效果不好。我还想写C:\ file.csv进行打印和报告等。请告知如何实现所需的输出。

1 个答案:

答案 0 :(得分:0)

您可以paste要嵌套在一起的两个变量。由于项目将按字典顺序排序,因此您需要对临时变量进行零填充,以获得数字排序。

xtabs(time3~wind+paste(sprintf("%02d",temp),RH,sep=":")+paint,dfx)
, , paint = paintA

    paste(sprintf("%02d", temp), RH, sep = ":")
wind 05:0 05:35 05:75 05:95 11:0 11:35 11:75 11:95 20:0 20:35 20:75 20:95
   1   56     0   104     0   88     0   136     0  120     0    72     0
   2    0   128     0    80    0    64     0   112    0    96     0   144

, , paint = paintB

    paste(sprintf("%02d", temp), RH, sep = ":")
wind 05:0 05:35 05:75 05:95 11:0 11:35 11:75 11:95 20:0 20:35 20:75 20:95
   1   56     0   104     0   88     0   136     0  120     0    72     0
   2    0   128     0    80    0    64     0   112    0    96     0   144

, , paint = paintC

    paste(sprintf("%02d", temp), RH, sep = ":")
wind 05:0 05:35 05:75 05:95 11:0 11:35 11:75 11:95 20:0 20:35 20:75 20:95
   1   56     0   104     0   88     0   136     0  120     0    72     0
   2    0   128     0    80    0    64     0   112    0    96     0   144