我正在为大量数据做一些相当基本的描述性统计。我写了一个函数来尝试获取所需的统计数据。
我想在数据帧的底部创建一个新行,其中一个元素是因子(“total”),另一个元素是数字(其他行的总和)。
以下是此代码的示例:
创建数据帧
df <- data.frame(
pop = c(201:250),
age = factor(rep(c("20-29", "30-39", "40-49", "50-59", "60-69"), 10)),
year = factor(rep(c(2012, 2013, 2014, 2015, 2016), 10)) )
编写函数进行聚合
DiabMort_fun <- function(VDRpop, VDRage, nyrs, nrows) {
Aggregate_fun <- function(pop, ag1, nyrs, nrows, names_list) {
popbylist <- data.frame(aggregate(pop, by = list(Category = ag1), FUN=sum))
popbylist$mean <- (popbylist$x / nyrs)
colnames(popbylist) = names_list
popbylist[nrows,] <- c("total", sum(popbylist[2]), sum(popbylist[3]))
return(popbylist)
}
VDRbyage <- Aggregate_fun(pop = VDRpop, ag1 = VDRage, nyrs = nyrs, nrows = nrows,
names_list = c("Age", "Num_pop_VDR", "Mean_pop_VDR"))
return(VDRbyage)
}
运行此函数
test <- DiabMort_fun(VDRpop = df$pop, df$age,
nyrs = 5, nrows = 5)
当我运行此操作时,会收到以下错误消息:
警告消息:
在里面
[<-.factor
(
*tmp*
,iseq,value=“total”):
因子级别无效,生成NA
“总计”列现在是c(NA,11275,2255)
有人知道如何在此函数中创建新行,将因子级别扩展为包含“total”吗?函数中的相关代码为:
popbylist[nrows,] <- c("total", sum(popbylist[2]), sum(popbylist[3]))
谢谢