I have a function called diseaseMutation that needs to be ran on data frame joint2 multiple times, each with different conditions. For instance, three copies of the code would look like the following:
Colon <- diseaseMutation(joint2, "Colon/Colorectal Cancer")
Bladder <- diseaseMutation(joint2, "Bladder Cancer")
Lung <- diseaseMutation(joint2, "Lung Cancer")
How can I put this function into a for loop for the diseases and save an output that has a name similar to its disease? So far, I tried to initialize the output into a list, but am not sure on how to continue.
fullList <- unique(joint2$disease)
listofdfs <- list()
for(i in 1:length(fullList)) {
}
This is literally a purpose and strength of the *apply
family of functions.
results <- sapply(unique(joint2$disease),
function(j) diseaseMutation(joint2, j),
simplify = FALSE)
results <- lapply(unique(joint2$disease),
function(j) diseaseMutation(joint2, j))
The first has the advantage of saving the disease name as the name of each element, and since we've included simplify=FALSE
, it will still always return a list
. The second is perhaps code-golf-better but does not include names. They can easily be applied post-run using names
if needed, but in that case just start with sapply
.
If you must have a for
loop (and there are times it is justified... though this doesn't scream out here):
out <- list()
diseases <- unique(joint2$disease)
for (i in seq_along(diseases)) {
out[i] <- diseaseMutation(joint2, diseases[i])
}
## or a named-variety
for (d in diseases) {
out[d] <- diseaseMutation(joint2, d)
}
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.