1

I have written several functions and want to only apply them to the last two columns of an input CSV file. The question is how to convert the last two columns to vectors and apply my functions to them?

myAvg <- function(anyVector){ average <- sum(anyVector) / length(anyVector) return(average) } mySD <- function(anyVector){ std_Dev <- sqrt(sum((anyVector - mean(anyVector)) ^ 2 / (length(anyVector) - 1))) return(std_Dev) } myRange <- function(anyVector){ myRange <- max(anyVector) - min(anyVector) return(myRange) } data <- read.csv("CardioGoodnessFit.csv") print(data) 

Here is the first couple lines of the file

2
  • 2
    please include the data as text Commented Sep 7, 2017 at 5:27
  • This is not a range myRange<-max(anyVector)-min(anyVector) Commented Sep 7, 2017 at 6:23

2 Answers 2

3

As @Mako212 suggested this can be simple achieved by using the apply function in R:

avg = apply(data[,c('Income','Miles')],MARGIN=2,FUN=myAvg) sdev = apply(data[,c('Income','Miles')],MARGIN=2,FUN=mySD) 

Function myAvg will be applyied to each column of the subset of data. Columns of interest can be specified either by providing the names of the columns or column numbers in a vector. Apply is generally used for a matrix or data.frame type object. While MARGIN provides the option to apply the FUN column-wise (MARGIN = 2) , row-wise (MARGIN=1) or both(to each element of data MARGIN=c(1,2))

Sign up to request clarification or add additional context in comments.

Comments

2

There is no need to convert to vectors (or in this case, even to write functions) if you use e.g. dplyr:

library(dplyr) # means data %>% summarise(avg = mean(Income)) data %>% summarise(avg = mean(Miles)) # standard deviations data %>% summarise(sdev = sd(Income)) data %>% summarise(sdev = sd(Miles)) # range data %>% summarise(range = max(Income) - min(Income)) data %>% summarise(range = max(Miles) - min(Miles)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.