0

I'm fairly new to R and currently trying to write a for loop to calculate and add to the currently existing dataset.

It's not exactly what I'm trying to do but the idea is as follows.

R code below:

x1 = rnorm(n=100, m=0, sd=1)
x2 = rnorm(n=100, m=3, sd=2)
x3 = x1 * 4.12
d = data.frame(x1,x2,x3)

d$result[1] = (d[1,1] + d[1,2]) / d[1,3]
d$result[2] = (d[2,1] + d[2,2]) / d[2,3]
d$result[3] = (d[3,1] + d[3,2]) / d[3,3]
.
.
.
.
d$result[100] = (d[100,1] + d[100,2]) / d[100,3]

And I'm fully aware that I could add a result variable by simply applying

d$result = (x1 + x2) / x3

But as mentioned, as this isn't what I'm currently trying to, it'd be much appreciated if someone could please help me write the for loop mentioned above.

Many thanks in advance.

3
  • Could you explain more about what you are trying to do exactly and how d$result = (x1 + x2) / x3 may not fulfill your need? Otherwise the for-loop-version solution could be for (i in 1:100) {d$result[i] = (d[i,1] + d[i,2]) / d[i,3]}. Commented Mar 4, 2018 at 4:23
  • Note that the example is not reproducible without set.seed given that it employs random numbers. Commented Mar 4, 2018 at 4:24
  • @ytu I'm currently trying to see what could possibly be the best model for generating association rules. My data has 3 possible outcome and each model requires minimum support (which I have fixed) and minimum confidence level. I have 129 possible different models with 3 different possible combinations of minimum confidence level. I need to run a for loop to generate various stats that will evaluate how well a model has performed. Hope this makes sense. Commented Mar 4, 2018 at 4:41

2 Answers 2

1

Try any of these:

transform(d, result = (x1 + x2) / x3)

d$result <- (d[, 1] + d[, 2]) / d[, 3]

d$result <- (d[[1]] + d[[2]]) / d[[3]]

d$result <- (d$x1 + d$x2) / d$x3

d$result <- with(d, (x1 + x2) / x3)

n <- nrow(d)
d$result <- sapply(seq_len(n), function(i) (d[i, 1] + d[i, 2]) / d[i, 3])

n <- nrow(d)
d$result <- NA_real_  # optional but pre-allocation is more efficient
for(i in seq_len(n)) d$result[i] <- (d[i, 1] + d[i, 2]) / d[i, 3]
Sign up to request clarification or add additional context in comments.

1 Comment

The last one should work like a charm for exactly what I'm currently trying to do. @G.Grothendieck Thank you so much!!
0

One option if there are NA elements will be to use rowSums

d$result <- rowSums(d[1:2], na.rm = TRUE)/d[,3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.