1

My data frame is called Subs.

My variables are REV_4, REV_5, REV_6 etc

I want to create new variables to calculate percentage change of revenue.
Eg: d.rev.5 <- Subs$REV_5/Subs/$REV_4 -1

I would like to use a loop to create these new variables. I've tried this:

for(i in 5:10){
Subs$d.data.[i] <- Subs$REV_[i]/Subs$REV_[i-1] - 1 }

But it doesn't work. I suspect it's not recognizing the i as part of the variable name.

Is there any way to get around this? Thank you so much.

3
  • why do you want to use a loop? Subs$d.rev.5 <- Subs$REV_5 / (Subs$REV_4 - 1) should do. Commented Feb 28, 2016 at 6:57
  • Oh I guess I didn't explain myself properly. I have about 40 different revenue variables, i.e. REV_4, REV_5.......REV_39, REV_40 etc. and I was hoping to find a faster way to create a new variable to calculate their percentage change. Commented Feb 28, 2016 at 7:12
  • You should update your question with the output of dput(head(Subs)) so others can see the structure of the data you're working with, and can therefore give you a solution Commented Feb 28, 2016 at 7:13

1 Answer 1

2

You can't reference columns like you're attempting (Subs$REV_[i]), you need to create a string to represent the column.

What I think you're trying to do is (in the absense of your data I've created my own)

set.seed(123)
Subs <- data.frame(rev_1 = rnorm(10, 0, 1),
                   rev_2 = rnorm(10, 0, 1),
                   rev_3 = rnorm(10, 0, 1),
                   rev_4 = rnorm(10, 0, 1))

for(i in 2:4){
  ## looping over columns 2-4
  col1 <- paste0("rev_", i)
  col2 <- paste0("rev_", i - 1)

  col_new <- paste0("d.rev.", i)

  Subs[, col_new] <- Subs[, col1] / Subs[, col2]

}

## A note on subsetting a data.frame
Subs$rev_1   ## works
i <- 1
Subs$rev_[i] ## doesn't work
Subs[, rev_[i]] ## doesn't work
Subs[, "rev_1"] ## works
Subs[, paste0("rev_", i)] ## works
## because
paste0("rev_", i)  ## creates the string:
[1] "rev_1"
Sign up to request clarification or add additional context in comments.

3 Comments

why one should use Subs[, paste0("rev_", 2)] ? cannot you use Subs[, 2] or Subs[,i]
That was exactly what I needed. Thank you so much!
@Learner you're right, you can, I just assumed they wanted to reference the column by name

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.