Skip to content

Instantly share code, notes, and snippets.

@shravan-kuchkula
Created March 31, 2017 18:16
Show Gist options
  • Save shravan-kuchkula/c2f55baf5872bff38cb1dfdf80fdd3fb to your computer and use it in GitHub Desktop.
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.
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