Iterating down a column HELP!

hello, i am wondering why this code is not working. So i have a table of close prices and i am trying to create a new column called 'triangle' where if the close price of next line is greater than the close price the previous one, assign a value of 2 else assign a value of 1. I am getting an argument of length zero and i do not understand why

for(n in 2:nrow(data)) {
  if(data[n]$Close > data[n+1,]$Close) {
    data$triangle[n] <- 1
  }
  else
  {
    data$triangle[n] <- 2
  }
}

Hello,

Please can you follow the advice on FAQ: Tips for writing R-related questions.

You'll see a reprex will help. Currently, we have no idea about what data is and you error may comes from it and how you test it in if.

Your current code is likely not working because your n gets out of bounds. When you are on your last value of n, you try to access data[nrow(data)+1, ]$Close but that doesn't exist. You might want your loop to go from 1:(nrow(data)-1)

I would use the lag or lead function to solve as shown here - it's a bit unclear which one you want but one of these two examples should be it:

library(tidyverse)

data <- tibble(Close=c(1, 2, 3, 5, 4, 6, 2, 2)) %>%
  mutate(if_else(Close < lead(Close), 2, 1))
data
#> # A tibble: 8 x 2
#>   Close `if_else(Close < lead(Close), 2, 1)`
#>   <dbl>                                <dbl>
#> 1     1                                    2
#> 2     2                                    2
#> 3     3                                    2
#> 4     5                                    1
#> 5     4                                    2
#> 6     6                                    1
#> 7     2                                    1
#> 8     2                                   NA

data <- tibble(Close=c(1, 2, 3, 5, 4, 6, 2, 2)) %>%
  mutate(if_else(Close > lag(Close), 2, 1))
data
#> # A tibble: 8 x 2
#>   Close `if_else(Close > lag(Close), 2, 1)`
#>   <dbl>                               <dbl>
#> 1     1                                  NA
#> 2     2                                   2
#> 3     3                                   2
#> 4     5                                   2
#> 5     4                                   1
#> 6     6                                   2
#> 7     2                                   1
#> 8     2                                   1

Created on 2020-01-13 by the reprex package (v0.3.0)

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.