2

我无法弄清楚矢量的格式。我需要在 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))

这就是输出的样子。

4

2 回答 2

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 
于 2020-05-24T06:01:03.623 回答
0

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

如果你想对 height 的输出求和heightdata,它们存储在namesofheightdata但它是字符格式,将其转换为数字和sum

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

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

sum(unique(cystfibr$height))
#[1] 3177
于 2020-05-24T03:44:20.757 回答