-1

I have a folder with several files. From each file I would like to select a cell (third row, 5th column) and bind them into one single column. Here's what I've got so far:

  fnames1 <- scan(file.choose(), what = "character", quiet = TRUE)
  print(fnames1)
  for (i in fnames1) 

  {
  date.time <- read.table(paste("...",i, sep = ""), skip = 2, nrows = 1)
  timecol <- paste(date.time[, 5])
  time <- cbind(timecol)}

but I'm still just getting several individual cells instead of one row with all the cells in it.

Any help will be very much appreciated!

EDIT: Answers to MrFlick: when prompted, I choose a file that contains the names of all the files in the folder from which I want to extract the cell I need. This is where fnames1 comes from. Time is a variable I'm creating to try to concatenate all the cells together (which is obviously not working). Adding that pasteafter the read table is the only way I've managed to get the loop working... I'm very new to R and I've been working with trial and error.

  • 1
    Where exactly are you "getting" these values? Are you looking at the `time` variable after the loop? Do you define/initialize it before the loop? What's with the `paste("...",i)` in the `read.table`? So `fnames1` comes from a text file with the names of all the files? – MrFlick Jun 13 '14 at 02:04
  • @MrFlick: Thank you for looking at my post. I've added some edits to answer your questions. – user3713629 Jun 13 '14 at 02:35
  • fyi, you can get a list of files in a directory using `list.files()` – rrs Jun 13 '14 at 03:26

1 Answers1

0

I'm still not sure I completely understand, But what about

fnames1 <- scan(file.choose(), what = "character", quiet = TRUE)
print(fnames1)
time <- sapply(fnames, function(fn) {
     date.time <- read.table(fn, skip = 2, nrows = 1)
     date.time[, 5]
})
print(time)

Here we use sapply to loop over the file names rather than a for loop which also will automatically create a vector of the correct size for us using the date.time[3,5] values.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thank you, sapply is new to me. But somehow I need to input the path to the folder where all the files are... where do I do this? – user3713629 Jun 13 '14 at 02:57
  • @user3713629 `read.table` would be a good place `read.table(file.path("directory",fn), skip = 2, nrows = 1)` – MrFlick Jun 13 '14 at 03:05