1

Iam trying to calculate multiple values with my own function from a dataframe. The function currently returns only one value in a dataframe. It seems my for loop is not working correctly. I've also tried to put the results in a new list...

My dataframe:

 A B C D E ES -0.03 -0.08 -0.07 -0.03 -0.11 

My function:

w <- function(x){ for(i in 1:length(x)) { return( (1/x[i]) / (sum(1/x)) ) } } 

The formula is correct because of the result. Does anyone have a solutions for my problem? Thanks!

1
  • It's not entirely clear what you're trying to calculate. In the denominator, do you want to sum up values down each column, or across each row? Commented May 17, 2013 at 12:33

2 Answers 2

5

You shouldn't use a for loop, but vectorize your function and apply it directly to your vector. Something like this :

R> v <- c(-0.03, -0.08, -0.07, -0.03, -0.11) R> (1/v)/sum(1/v) [1] 0.32506596 0.12189974 0.13931398 0.32506596 0.08865435 
Sign up to request clarification or add additional context in comments.

Comments

5

Juba's answer solves this problem but if you want to return multiple distinct objects from a function you can actually do that, too:

f <- function(x) { m.x <- mean(x) sd.x <- sd(x) return(list(Mean = m.x, SD = sd.x)) } 

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.