Hey everyone I'm new to Rstudio and I'm taking a class and is stuck trying to make a function that inputs a vector then I have to run some standard test like mean, median, mode and having that come out with a vector as well with the name so mean= 5 and etc.
part2_function <- function(x){
length(x)
sum( is.na(x))
mean(x)
median(x)
max(x)
min(x)
sd(x)
return(x)
}
this is what I have kinda put together so far but super lost still.
Thanks!
how can I put words in front of the values. My vector needs to output that the mean=5. I've tried to put "mean=" inside that vector and keep getting errors. Do I need to write it as a different line or inside the vector
Please show your actual code. Also, note the difference between the two vectors in the code below. The first is a named vector of numbers and the second is a vector of characters. I suspect you want a named vector.
part2_function <- function(x){
<- ifelse(is.numeric(x),x,"Error: must be a numeric vector") #to make sure a string gives an error. not sure what to put in front of the vector
c (length(x), sum( is.na(x)), mean(x), median(x), max(x), min(x), sd(x))
}
currently my code.
I need my results to come out like this
c(n=33, numberNA=5, mean=5, median=4, max=10, min=1, stdev=3)
Given you are newer to R and asking this question in the context of a class, I think it would be
valuable to you to point out a resource like the functions chapter of r4ds, 19 Functions | R for Data Science, and ask you to review it.
Looks like you are struggling on what kind of return value you want your function to give.
You want to return the top vector, but name each of those values. In the bottom vector, you named a bunch of the values.
Looks like you just need to connect the dots there, e.g. you can return something like
c(length = length(x), sum = sum((is.na(x)), ..., )
Hi you can create a function like this, which return a list with all you need
name.function <- function(x) {
list.return <- list(length = length(x), sum = sum(is.na(x)), mean = mean(x), median = median(x), max = max(x), min = min(x), sd = sd(x))
return(list.return)
}
tmp <- c(1,2,3,4,5)
res <- name.function(tmp)
res
$length
[1] 5