For loop Not working

rstudio

#1

Here is my simple code

setwd("C:\\Users\\USER 1\\Downloads\\R File")

cena <- c("AA","BB","CC","DD","EE","FF")

kofi <- data.frame()

for (i in cena) {
  
  filename <- paste(i,".csv",sep="")
  
  randy <- read.csv(filename)
  randy$file <- i
   kofi <- rbind(randy,kofi)
}
kofi <- kofi[order(kofi$file),]
head(kofi)
#>         Date   Open   High    Low  Close   Volume Change ChangePerc Symbol
#> 6 20-10-2017 156.61 157.75 155.96 156.25 23907540   0.27  0.1728000   aapl
#> 5 19-10-2017 156.75 157.08 155.02 155.98 42357420  -3.78 -2.4233876   aapl
#> 4 18-10-2017 160.42 160.71 159.60 159.76 16252850  -0.71 -0.4444166   aapl
#> 3 17-10-2017 159.78 160.87 159.23 160.47 18969700   0.59  0.3676700   aapl
#> 2 16-10-2017 157.90 160.00 157.65 159.88 24093300   2.89  1.8076057   aapl
#> 1 13-10-2017 156.73 157.28 156.41 156.99 16367780   0.99  0.6306134   aapl
#>   file
#> 6   AA
#> 5   BB
#> 4   CC
#> 3   DD
#> 2   EE
#> 1   FF


balor <- kofi$High
balor
#> [1] 157.75 157.08 160.71 160.87 160.00 157.28
str(balor)
#>  num [1:6] 158 157 161 161 160 ...

balor[2]
#> [1] 157.08
folly <- 0


for (i in balor) {
 
folly <- balor[i]+ balor[i+1] 
  
  print(folly[i])
}
#> [1] NA
#> [1] NA
#> [1] NA
#> [1] NA
#> [1] NA
#> [1] NA

It shows NA.
expected output,314.83 (157.75+157.08),317.79 (157.08+160.71) etc
Are you getting any idea, what wrong i have done.

Thanks,
snandy2011


#2

You have defined balor <- kofi$High.

kofi$High is not an integer vector. So on the first pass of the for loop, you are asking for balor[157.75], which doesn't make much sense.

You probably want to use for (i in seq_along(balor))

The next issue you will have is that folly is a length 1 vector. You may need to reconsider what the end result of folly is supposed to be.


#3

What you’re trying to accomplish with your second for loop can also be done like this in R:

(if you know that balor always has 6 values)

balor[1:5] + balor[2:6]

A more general version, for variable length balor (or for abstracting out into a small utility function)

balor[1:length(balor) - 1] + balor[2:length(balor)]

(For use in a function, you’d need to also check for invalid balor, e.g. length 1 or 0)


#4

This is one of the coolest solution.I just wanted to achieve this by for loop.but, did not think this simplest way. Some time we forget to go simple way.

Thank you very much for your awesome solution.

Thanks,
snandy2011


#5

I'd just like to add, that the above usually in R, would be done something along the lines of:

my_csv_files = list.files(path = "/path/to/my/csv_files/", pattern = "csv$", full.names = TRUE)
my_data = lapply(my_csv_files, read.csv)
my_data = do.call(rbind, my_data)

:slightly_smiling_face:


#6

Nice solution.. without for loop.. Thanks a lot..