【问题标题】:R program to calculate some statsR程序计算一些统计数据
【发布时间】:2013-09-19 08:59:05
【问题描述】:

我有一个data.frame,数据分为 16 列:第一个是名称,第二个是日期,另外 14 个是指标。

喜欢:

      name  date hight weight ....
      John  1950 1.81  78
      John  1948 1.60  60
      Susan 1985 1.40  40    .
      Susan 1995 1.45  60 

我想为每个名字执行一些基本统计数据(平均值、标准差等),即:约翰身高、体重等的平均值; Susan、身高、体重等的平均值。

为了做到这一点,我先写了一个函数:

 mysummary <- function(x){
  setNames(c(mean(x), sd(x), skewness(x), kurtosis(x)),
           c("Mean", "SD", "Skewness", "Kurtosis"))
}

但是当我用命令执行它时:

    summaryStatic = by(data[,c('height','weight')], list(data$name),  function(x){
  y <- sapply(x, FUN =mysummary(as.numeric(x)))
  return(y)
})  

但我收到以下错误:

Error in mean(x) : (list) object cannot be coerced to type 'double'

我知道这与data.frame 结构有些相关。如您所见,我尝试使用as.numeric(x) 解决它,但没有成功。

【问题讨论】:

  • 你怎么可能有一个由字符、日期和数字组成的matrix?你有一个data.frame 或一个只有字符的矩阵,只包含数字和日期(但强制转换为字符)?
  • 请改进您的问题 - 它的结构不完善,而且不知何故没有重点。这让人很难理解,尤其是回答它。
  • 感谢您的评论。一个数据矩阵...我有一个 .txt 文件,为了读取它,我使用了 read.delim 函数。
  • 学习一些正确的术语,这个问题大部分都会自行解决。
  • 如果您发布了数据集前五列的前五行以及您正在使用的 R 代码,这可能会有所帮助。无论如何,我通常使用read.tableread.csv。也许添加na.strings = "NA"。也许尝试用 Google 搜索 read.table 示例。

标签: r


【解决方案1】:

我不确定,但也许这可以满足您的需求。如果是这样,只需添加更多汇总统计信息:

my.data <- read.table(text = '
      name  date height weight
      John  1950 1.81  78
      John  1948 1.60  60
      Susan 1985 1.40  40
      Susan 1995 1.45  60
', header = TRUE, stringsAsFactors = FALSE)

with(my.data, aggregate(height ~ name, FUN = function(x) c( SD = sd(x), MEAN = mean(x) ) ))

with(my.data, aggregate(weight ~ name, FUN = function(x) c( SD = sd(x), MEAN = mean(x) ) ))

with(my.data, aggregate(cbind(height, weight) ~ name, FUN = function(x) c( SD = sd(x), MEAN = mean(x) ) ))

   name  height.SD height.MEAN weight.SD weight.MEAN
1  John 0.14849242  1.70500000  12.72792    69.00000
2 Susan 0.03535534  1.42500000  14.14214    50.00000

with(my.data, aggregate(my.data[,3:4], by = list(name), FUN = function(x) c( SD = sd(x), MEAN = mean(x) ) ))

  Group.1  height.SD height.MEAN weight.SD weight.MEAN
1    John 0.14849242  1.70500000  12.72792    69.00000
2   Susan 0.03535534  1.42500000  14.14214    50.00000

【讨论】:

    猜你喜欢
    • 2015-04-15
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多