R 中混合数据的摘要和描述性 table
summary and descriptive table for mixed data in R
我想创建一个函数来计算一些我可以应用于任何数据集的预先确定的汇总统计量度。我将从这里的示例开始,但这是针对可能具有多种数据类型的数据集 - 例如字符、因子、数字、日期、包含空值等。
如果数据都是数字,我可以很容易地做到这一点——但是处理 IF 场景 w/apply、sapply 等是我 运行 遇到语法问题的地方。
当它全是数字时我很棒,因为我可以做 new_df = data.frame(min = sapply(mydf, 2,min).....等等....等等)。当它像下面的示例一样复杂时,我无法正确理解语法。
在下面的示例中,我有一个 3 列的数据框:
- 全是数字
- 带空值的数值
- 编码为因子的分类数据列
我要计算:
- 类型...(字符、因子、日期、数字等)
- 意味着...当数据类型显然是数字时,并且排除空值
- 数据集中空值的数量
我认为这很简单,我可以从这里 运行 使用它..
复制并粘贴此代码和名称作为数据框的变量:
structure(list(allnumeric = c(10, 20, 30, 40), char_or_factor = structure(c(2L,
3L, 3L, 1L), .Label = c("bird", "cat", "dog"), class = "factor"),
num_with_null = c(10, 100, NA, NA)), .Names = c("allnumeric",
"char_or_factor", "num_with_null"), row.names = c(NA, -4L), class = "data.frame")
预期解数据框(复制并分配给变量):
structure(list(allnumeric = structure(c(3L, 2L, 1L), .Label = c("0",
"25", "numeric"), class = "factor"), char_or_factor = structure(c(2L,
NA, 1L), .Label = c("0", "character"), class = "factor"), num_with_null = structure(c(3L,
2L, 1L), .Label = c("2", "55", "numeric"), class = "factor")), .Names = c("allnumeric",
"char_or_factor", "num_with_null"), row.names = c("type", "mean",
"num_nulls"), class = "data.frame")
我们可以使用 sapply
遍历列,获取 class
、mean
和 NA 元素的数量,连接 (c(
) 并转换为 data.frame
as.data.frame(sapply(df1, function(x) c(class(x), mean(x, na.rm=TRUE),
sum(is.na(x)))), stringsAsFactors=FALSE)
我想创建一个函数来计算一些我可以应用于任何数据集的预先确定的汇总统计量度。我将从这里的示例开始,但这是针对可能具有多种数据类型的数据集 - 例如字符、因子、数字、日期、包含空值等。
如果数据都是数字,我可以很容易地做到这一点——但是处理 IF 场景 w/apply、sapply 等是我 运行 遇到语法问题的地方。 当它全是数字时我很棒,因为我可以做 new_df = data.frame(min = sapply(mydf, 2,min).....等等....等等)。当它像下面的示例一样复杂时,我无法正确理解语法。
在下面的示例中,我有一个 3 列的数据框:
- 全是数字
- 带空值的数值
- 编码为因子的分类数据列
我要计算:
- 类型...(字符、因子、日期、数字等)
- 意味着...当数据类型显然是数字时,并且排除空值
- 数据集中空值的数量
我认为这很简单,我可以从这里 运行 使用它..
复制并粘贴此代码和名称作为数据框的变量:
structure(list(allnumeric = c(10, 20, 30, 40), char_or_factor = structure(c(2L,
3L, 3L, 1L), .Label = c("bird", "cat", "dog"), class = "factor"),
num_with_null = c(10, 100, NA, NA)), .Names = c("allnumeric",
"char_or_factor", "num_with_null"), row.names = c(NA, -4L), class = "data.frame")
预期解数据框(复制并分配给变量):
structure(list(allnumeric = structure(c(3L, 2L, 1L), .Label = c("0",
"25", "numeric"), class = "factor"), char_or_factor = structure(c(2L,
NA, 1L), .Label = c("0", "character"), class = "factor"), num_with_null = structure(c(3L,
2L, 1L), .Label = c("2", "55", "numeric"), class = "factor")), .Names = c("allnumeric",
"char_or_factor", "num_with_null"), row.names = c("type", "mean",
"num_nulls"), class = "data.frame")
我们可以使用 sapply
遍历列,获取 class
、mean
和 NA 元素的数量,连接 (c(
) 并转换为 data.frame
as.data.frame(sapply(df1, function(x) c(class(x), mean(x, na.rm=TRUE),
sum(is.na(x)))), stringsAsFactors=FALSE)