Skip to content

Instantly share code, notes, and snippets.

@ggorlen
Last active April 18, 2023 18:40
Show Gist options
  • Save ggorlen/60fbe6dac18d6f11621a24866cf44e06 to your computer and use it in GitHub Desktop.
Save ggorlen/60fbe6dac18d6f11621a24866cf44e06 to your computer and use it in GitHub Desktop.
R gotchas

R gotchas

Weird vectorized string appends

Wrong:

result <- c()
result <- c(result, "foo")
result <- c(result, paste0(rep("X", 3), "z")) # => [1] "foo" "Xz"  "Xz"  "Xz" 
print(result) # => [1] "foo\nXz\nXz\nXz"
print(paste(result, collapse="\n"))

Fix:

result <- c()
result <- c(result, "foo")
result <- c(result, paste0(paste0(rep("X", 3), collapse=""), "z"))
# or: result <- c(result, paste0(strrep("X", 3), "z"))
print(result) # => [1] "asdf" "XXXz"
print(paste(result, collapse="\n")) # => [1] "asdf\nXXXz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment