2

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?

2 Answers 2

4

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)
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Pascal. But I want to use the message function and display to the user. The code works but when I wrap it with message it doesn't work :( <br> This little code is going to be part of my very long code which displays messages to user at certain points. I have re-edited my main question and put focus on message.
Thanks so much for your time @Pascal. I have posted a solution below. I have done it using the traditional way and using 1 for loop now.
There is also one loop in my solution.
I couldn't find a clean solution without the for loop. It is annoying me.
1

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
}

Comments

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.