Nick
Nick

Reputation: 21

Summing a specific vector index

I'm having trouble figuring out how vectors are formatted. I need to find the average height of participants in the cystfibr package of the ISwR library. When printing the entire height data set it appears to be a 21x2 matrix with height values and a 1 or 2 to indicate sex. However, ncol returns a value of NA suggesting it is a vector. Trying to get specific indexes of the matrix (heightdata[1,]) also returns an incorrect number of dimensions error.

I'm looking to sum up only the height values in the vector but when I run the code I get the sum of the male and female integers. (25)

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

This is what the output looks like.

Upvotes: 2

Views: 87

Answers (2)

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

You can convert the cystfibr to a dataframe format to find out the sum of all vectors present in the data.

install.packages("ISwR")
library(ISwR)

data <- data.frame(cystfibr) # attach and convert to dataframe format

As there are no unique identifier present in the data, so done sum across observations

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 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

table gives you the count of values in the vector.

If you want to sum the output of height from heightdata, they are stored in names of heightdata but it is in character format, convert it to numeric and sum.

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

which is similar to summing the unique values of height.

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

Upvotes: 0

Related Questions