【问题标题】:Summing a specific vector index对特定向量索引求和
【发布时间】:2020-05-24 03:36:38
【问题描述】:

我无法确定矢量的格式。我需要在 ISwR 库的 cystfibr 包中找到参与者的平均身高。打印整个高度数据集时,它似乎是一个 21x2 矩阵,具有高度值和 1 或 2 表示性别。但是,ncol 返回值 NA 表明它是一个向量。尝试获取矩阵的特定索引 (heightdata[1,]) 也会返回不正确的维数错误。

我只想总结向量中的高度值,但是当我运行代码时,我得到了男性和女性整数的总和。 (25)

install.packages("ISwR")
library(ISwR)
attach(cystfibr)
heightdata = table(height)
print(heightdata)
print(sum(heightdata))

这就是output 的样子。

【问题讨论】:

    标签: r vector column-sum


    【解决方案1】:

    您可以将 cystfibr 转换为数据帧格式,以找出数据中存在的所有向量的总和。

    install.packages("ISwR")
    library(ISwR)
    
    data <- data.frame(cystfibr) # attach and convert to dataframe format
    

    由于数据中不存在唯一标识符,因此对观察结果求和

    apply(data [,"height", drop =F], 2, sum) # to find out the sum of height vector
    
    height 
    3820 
    
    
    unlist(lapply(data , sum)) 
    
    age    sex height weight    bmp   fev1     rv    frc    tlc  pemax 
    362.0   11.0 3820.0  960.1 1957.0  868.0 6380.0 3885.0 2850.0 2728.0 
    
    sapply(data, sum) 
    
    age    sex height weight    bmp   fev1     rv    frc    tlc  pemax 
    362.0   11.0 3820.0  960.1 1957.0  868.0 6380.0 3885.0 2850.0 2728.0 
    

    【讨论】:

    • 这里,你可以做矢量化的colSums
    【解决方案2】:

    table 为您提供向量中值的计数。

    如果要对来自heightdata 的高度输出求和,它们存储在heightdatanames 中,但它是字符格式,将其转换为数字和sum

    sum(as.numeric(names(heightdata)))
    #[1] 3177
    

    这类似于对height 的唯一值求和。

    sum(unique(cystfibr$height))
    #[1] 3177
    

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2020-09-02
      • 2013-11-05
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2022-09-23
      相关资源
      最近更新 更多