CuriousBeing
CuriousBeing

Reputation: 1632

Generate sequence in for loop

This has probably been answered, but I couldn't find the solution to my specific problem: I am looking for a certain file type (for eg. jpeg) and printing to the user a message using the message() function. But along with the message I want to print a sequence. The output should read:

1. Found filename at System time.
2. Found filename2 at System time. 

Unfortunately, my output is:

1 Found filename at System time
2 Found filename at System time
1 Found filename2 at System time
2 Found filename2 at System time

My Code:

library(tools)
setwd("/Users/RLearner/Desktop/TEMP")
a<-list.files(getwd(), recursive=TRUE)
for (f in a)
  for (i in 1:length(a))
    if (file_ext(f)=="jpeg")
    {
      message(paste(i, "Found", f, "-", Sys.time(), sep = " "))
    }

What am I doing wrong?

Upvotes: 2

Views: 71

Answers (2)

CuriousBeing
CuriousBeing

Reputation: 1632

I figured it out! If i declare a variable i<-0 and then increment it in the if statement, it works: My code:

library(tools)
setwd("/Users/RLearner/Desktop/TEMP")
a<-list.files(getwd(), recursive=TRUE)
i<-0
for (f in a)
if (file_ext(f)=="jpeg")
{
message(paste(i+1, "Found", f, "-", Sys.time(), sep = " "))
i<-i+1
}

Upvotes: 1

user3710546
user3710546

Reputation:

Isn't the following enough?

setwd("/Users/RLearner/Desktop/TEMP")
a <- list.files(getwd(), pattern="*jpeg$", recursive=TRUE)

out <- paste(seq_along(a), "Found", "-", a, Sys.time(), sep = " ")

Edit

I couldn't find a solution by simply feed message with out. There is still need for a for loop. If someone could find a wrapping, please feel free to edit.

for (ii in out){
  message(ii)
}

Upvotes: 4

Related Questions