重命名列表和csv输出

时间:2017-09-27 11:07:25

标签: r list typeof quantile

我正在尝试从基于此的数据框输出一些分位数结果:

result<- as.data.frame(tapply(df$Nbdays,list(df$Color,df$age),function(x)
round(quantile(x),digit=1)))

我需要输出类似于:

enter image description here

尝试以xls输出时

write.table(res6,file='ChGenAgebis.xls',sep='\t',row.names=F,na='0',append = T,fileEncoding = "latin1")

我遇到了这个错误:

  

.External2中的错误(C_writetable,x,file,nrow(x),p,rnames,sep,   eol,'EncodeElement'中未实现的类型'list'

所以首先如何在xls

中输出数据帧

其次是可以重命名列表列表而不是:

    str(res6)

    'data.frame':   6 obs. of  5 variables:
     $ [0-25[        :List of 6
      ..$ Yellow : Named num  1.0    4.5    7.0 8.5 12.0
      .. ..- attr(*, "names")= chr  "0%" "25%" "50%" "75%" ...
      ..$ Yellow : Named num  2.0    4.3    7.5 9.5 22.0
      .. ..- attr(*, "names")= chr  "0%" "25%" "50%" "75%" ...
....

因为当我尝试更改列表名称时:

result<- as.data.frame(tapply(df$Nbdays,list(df$Color,df$age),function(x)round(quantile(x[,c("Min","1stQuartile","Median","3rdQuartile","Max")]),digit=1)))

我有这个错误

  

x [,c(“Min”,“1erQuartile”,“Median”,“3rdQuartile”,“Max”)中的错误]:   不正确的尺寸数

任何帮助?

1 个答案:

答案 0 :(得分:1)

以下是可能有用的代码段:

# example data
dat <- data.frame(color=sample(c("Yellow", "Green", "Red"), 100, replace=TRUE), age=sample(c("0-25", "25-50", "50-60"), 100, replace=TRUE), nbDays=rnorm(100), stringsAsFactors=FALSE)
idx <- which(dat[,"color"]=="Red" & dat[,"age"]=="25-50")
dat <- dat[-idx,]

# calculate statistics
myfun <- function(x) quantile(x, names=FALSE, digit=1)
res <- tapply(dat$nbDays, list(dat$color, dat$age), FUN=myfun)

# transform res to data.frame
colors <- c("Yellow", "Green", "Red")
ages <- c("0-25", "25-50", "50-60")
colkeys <- c("Min", "1st Quart.", "Median", "3rd Quart.", "Max")
one_age <- function(age) {
    ans <- res[colors, age]
    for (cl in colors) if(is.null(ans[[cl]])) ans[[cl]] <- rep(NA,5)
    ans <- t(do.call(cbind, ans))
    colnames(ans) <- colkeys
    return(ans)
}
res <- do.call(cbind, lapply(ages, one_age))

要为年龄段添加标题行,请考虑使用支持多个标题行的flextable包。正如您在问题的评论中已经提到的那样,read.table无法写入Excel,例如使用例如改为xlsxopenxlsx包。