Reputation: 387
Could you please help me?
I have a list
of matrices
read into R
. Each matrix was randomized 10 times, and then a metric was calculated for each randomization. I want to store the results in an organized data frame that reflects the sequence of randomizations.
How can I build a vector
with the sequence of filenames + numbers, so I know which result refers to which randomization? Later, I'll add this vector to a data frame
to label the results.
This is what my code looks like so far:
Let's assume I have a vector with the names of the files read into R and that it looks something like this:
files <- paste("file", seq(1:3), sep = "")
Each file was randomized 10 times and then a metric was calculated for each randomization:
rand <- seq(1:10)
Now I want to create a vector with a sequence of filenames and randomizations:
files.rand <- paste(files, rand, sep = "_")
The final sequence produced by this code does not reflect the actual sequence in which the randomizations were analyzed.
I need the sequence to look like this:
"file1_1" "file1_2" "file1_3" "file1_4" "file1_5"
"file1_6" "file1_7" "file1_8" "file1_9" "file1_10"
"file2_1" "file2_2" "file2_3" "file2_4" ...
The sequential numbers should be added to the name of file1, then they should be added to the name of file2, and so on, in order.
How could this result be achieved? Thank you!
Upvotes: 1
Views: 670
Reputation: 389047
You can use outer
:
c(t(outer(files, rand, paste, sep = '_')))
#[1] "file1_1" "file1_2" "file1_3" "file1_4" "file1_5" "file1_6"
#[7] "file1_7" "file1_8" "file1_9" "file1_10" "file2_1" "file2_2"
#[13] "file2_3" "file2_4" "file2_5" "file2_6" "file2_7" "file2_8"
#[19] "file2_9" "file2_10" "file3_1" "file3_2" "file3_3" "file3_4"
#[25] "file3_5" "file3_6" "file3_7" "file3_8" "file3_9" "file3_10"
Upvotes: 1
Reputation: 369
If you want each file to have each sequence pasted on the end in the order that you already have the files and sequence sorted, then I think you just want to use lapply
on a paste
function and unlist
it like so:
files.rand <- lapply(files,function(x) paste(x,rand,sep = "_"))
files.rand <- unlist(files.rand)
Upvotes: 1
Reputation: 1277
You can simply sort files.rand, but this would stumble over the alphanumeric order, which is not the same as numeric order. A simple workaround is to add leading zeros to your numbers (replace "%02i" with "%03i" for 100 random numbers etc.):
files.rand <- paste(files, sprintf("%02i", rand), sep = "_")
files.rand <- sort(files.rand)
Upvotes: 0