I am analysing PCA data. So I have to compare PC1 vs PC2, PC1 vs PC3 etc. I want to store thes ggplot objects into a vector. Until here no problem. I create a vector as:
Myplot <- vector('list',NumberToBeInserted)
and then I can run a for loop or an lapply. However, Let's say that in the near future I will need to analyse PC2 vs PC3 (until PC2 vs PCn) or more in general PCn-1 vs PCn. I need, therefore, to generate a lot of these vectors in order to store PC comparisons in a different set. Let's say I know to need 5 vectors similar to the one I proposed up above. How can I create a function that returns me these vectors?Does this question make sense or is it better to do it manually? Since I want to improve my skills with R I am quite curious
I'm not sure if this is what you are looking for, but supposing I have a list of 5 complex objects (for the example here they are all simple character strings, but the same method would work for any R object such as a ggplot):
big_list <- list(PC1 = "Complex object1",
PC2 = "Complex object2",
PC3 = "Complex object3",
PC4 = "Complex object4",
PC5 = "Complex object5")
If I want a new list that contains every pairwise combination of the elements in this list, I can do:
all_combos <- apply(combn(5, 2), 2, function(i) big_list[i])
names(all_combos) <- NULL
There are ten possible pairwise combinations out of 5 objects, so I will have a length-10 list, each of which is itself a length-two list of my complex objects:
str(all_combos)
#> List of 10
#> $ :List of 2
#> ..$ PC1: chr "Complex object1"
#> ..$ PC2: chr "Complex object2"
#> $ :List of 2
#> ..$ PC1: chr "Complex object1"
#> ..$ PC3: chr "Complex object3"
#> $ :List of 2
#> ..$ PC1: chr "Complex object1"
#> ..$ PC4: chr "Complex object4"
#> $ :List of 2
#> ..$ PC1: chr "Complex object1"
#> ..$ PC5: chr "Complex object5"
#> $ :List of 2
#> ..$ PC2: chr "Complex object2"
#> ..$ PC3: chr "Complex object3"
#> $ :List of 2
#> ..$ PC2: chr "Complex object2"
#> ..$ PC4: chr "Complex object4"
#> $ :List of 2
#> ..$ PC2: chr "Complex object2"
#> ..$ PC5: chr "Complex object5"
#> $ :List of 2
#> ..$ PC3: chr "Complex object3"
#> ..$ PC4: chr "Complex object4"
#> $ :List of 2
#> ..$ PC3: chr "Complex object3"
#> ..$ PC5: chr "Complex object5"
#> $ :List of 2
#> ..$ PC4: chr "Complex object4"
#> ..$ PC5: chr "Complex object5"
So to access the first pairing of objects I would do:
all_combos[[1]]
#> $PC1
#> [1] "Complex object1"
#>
#> $PC2
#> [1] "Complex object2"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.