Created
March 31, 2017 18:16
-
-
Save shravan-kuchkula/c2f55baf5872bff38cb1dfdf80fdd3fb to your computer and use it in GitHub Desktop.
A safer way to write a for loop in R. Use seq_along() to handle an empty data frame. Useful when using a for loop within a function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
df <- data.frame( | |
a = rnorm(10), | |
b = rnorm(10), | |
c = rnorm(10), | |
d = rnorm(10) | |
) | |
# Replace the 1:ncol(df) sequence | |
for (i in seq_along(df)) { | |
print(median(df[[i]])) | |
} | |
# Change the value of df | |
df <- data.frame() | |
# Repeat for loop to verify there is no error | |
for (i in seq_along(df)) { | |
print(median(df[[i]])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment