在数据框中创建一个新行,一个元素是一个因素,另一个是数字

Create a new row in a dataframe, one element is a factor, the other numeric

我正在为一大组数据做一些相当基本的描述性统计。我写了一个函数来尝试获取我需要的统计数据。

我想在数据框的底部创建一个新行,其中一个元素是一个因子 ("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)

当我 运行 执行此操作时,我收到以下错误消息:

Warning message: In [<-.factor(*tmp*, iseq, value = "total") : invalid factor level, NA generated

"totals" 列现在是 c(NA, 11275, 2255)

我想要的是 c("total", 11275, 2255)

有谁知道如何在此函数中创建一个新行来扩展因子水平以包括 "total"?函数内相关代码为:

popbylist[nrows,] <- c("total", sum(popbylist[2]), sum(popbylist[3]))

谢谢

您不需要将年龄和年份列作为因子;如果您跳过该步骤,并在第一个 data.frame() 调用中设置 stringsToFactors = FALSE,您的函数应该可以工作。

如果你真的想保留当前的顺序和数据类型,你可以将摘要行变成一个 1 行数据框,然后将其绑定到另一个框架。只需确保列名称匹配:

temp <- data.frame("total", sum(popbylist[2]), sum(popbylist[3]))
colnames(temp) = names_list
popbylist <- rbind(popbylist, temp)