0

Any experts with R programming can help me with this combining vector question?

R code shown below:

> maxTemps<-0
> for(i in printfilenames) {
+    file2 <- read.csv(i, row.names=1)
+    tempMax <-max(file2[1:145,1], na.rm=TRUE)
+    zero<-vector("numeric", 9)
+      for(i in tempMax) {
+         maxTemps<-tempMax+zero
+         print(tempMax)
+      }
+ }
[1] 24.3
[1] 24.1
[1] 19.4
[1] 21.2
[1] 25.4
[1] 28.7
[1] 22.7
[1] 23.2
[1] 24.2
> maxTemps
[1] 24.2 24.2 24.2 24.2 24.2 24.2 24.2 24.2 24.2

This is basically what I am getting.

The question require that my "maxTemps" output should be something like:

[1] 24.3 24.1 19.4 21.2 25.4 28.7 22.7 23.2 24.2

but I am getting:

[1] 24.2 24.2 24.2 24.2 24.2 24.2 24.2 24.2 24.2

Anyone can please help me where I got wrong here? Your helps are much appreciated.

Thanks!

Community
  • 1
  • 1
Sam
  • 19
  • 3

2 Answers2

1

Your question and code is very confusing:

  1. You execute

    maxTemps <- tempMax+zero
    

    at every iteration of your for loop, i.e. you do exactly the same calculation

  2. What vectors do you want to combine?

  3. You create a zero vector, zero, what's the point of adding zero to anything?

  4. To answer your question on output, you want something like:

    maxTemps = numeric(length(tempMax))
    maxTemps[i] = tempMax[i] + zero[i]
    
    ##Or not inside the for loop
    maxTemps = tempMax + zero
    ##OR
    maxTemps = tempMax
    
csgillespie
  • 59,189
  • 14
  • 150
  • 185
  • Im trying to create a numeric vector full of zeros first, then assigning value i of the vector on the i'th iteration of the loop. – Sam May 30 '13 at 11:04
  • Just one note: While a matter of style, the usage of `<-` as an assignment operator usually is preferred over `=` in the R-community. See http://stackoverflow.com/questions/1741820/assignment-operators-in-r-and – Thilo May 30 '13 at 15:01
0

I think what you're looking for is the following:

 max.temps <- rep(NA, length(printfilenames))

  for(i in 1:length(printfilenames)) {
    file2 <- read.csv(printfilenames[i], row.names=1)
    tempMax <-max(file2[1:145,1], na.rm=TRUE)
    max.temps[i] <- tempMax
   }

If I understand correctly, the problem isn't really one of combining vectors but calculating a single value (the maximum from each file) and inserting it into a vector.

Jon M
  • 1,157
  • 1
  • 10
  • 16