【问题标题】:R: How to automatically calculate the mean of all variables of a dataset? [duplicate]R:如何自动计算数据集所有变量的平均值? [复制]
【发布时间】:2015-07-06 04:26:40
【问题描述】:

我通过以下方式读入一个 csv 文件:

data = read.csv("airbnb.csv",header=T,sep=",")

数据有 100 多个变量,我需要计算所有变量的平均值。实际上我需要自动化以下操作:

mean(data$variable1)
mean(data$variable2)

....

有什么好方法可以做到这一点吗?例如。有循环吗?

【问题讨论】:

  • colMeans(data) 会更方便,如果有NA,可以使用na.rm=TRUE

标签: r


【解决方案1】:

您可以使用apply() 或@akrun 在评论中提到的colMeans()。后者针对这种情况进行了优化,因此对于大型数据集它可能会比前者表现更好。

您提到您有多种类型的数据,并且您只想选择数字列。这很容易,您只需事先识别数字列。这可以使用sapply()is.numeric() 来完成。

# Select numeric columns
data.numcols <- data[, sapply(data, is.numeric)]

# Using apply
all.means <- apply(data.numcols, 2, mean)

# Using colMeans
all.means <- colMeans(data.numcols)

如果您的列包含NA,您可以像这样排除NA 值:

# Using apply
all.means <- apply(data.numcols, 2, function(x) mean(x, na.rm = TRUE))

# Using colMeans
all.means <- colMeans(data.numcols, na.rm = TRUE)

【讨论】:

  • 对于这两个选项,我都收到一条错误消息,指出参数既不是数字也不是布尔值 -> 输出为 NA
  • 变量有不同的类型:因子、int和num(所以我想跳过因子变量,只计算int和num变量的平均值)
  • @NicoKriegschmichnet:查看我的更新答案。
猜你喜欢
  • 2020-12-15
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 2018-01-25
  • 2017-11-29
相关资源
最近更新 更多