Brian
Brian

Reputation: 163

How can I write for loop in R for creating an additional variable?

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.

Upvotes: 0

Views: 44

Answers (2)

akrun
akrun

Reputation: 887901

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

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

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 270248

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]

Upvotes: 1

Related Questions