Skip to content

Instantly share code, notes, and snippets.

@maurolepore
Last active September 14, 2021 12:49
Show Gist options
  • Save maurolepore/98d90b8866a1ea2e7ce0cca5e8b7e761 to your computer and use it in GitHub Desktop.
Save maurolepore/98d90b8866a1ea2e7ce0cca5e8b7e761 to your computer and use it in GitHub Desktop.
path_all_users <- "/path/to/all_users"
user_list <- c("user_1", "user_2")

# What you want: Same but simpler
path <- file.path(path_all_users, user_list)
path
#> [1] "/path/to/all_users/user_1" "/path/to/all_users/user_2"

# Same but for paths prefer file.path()
path <- paste0(path_all_users, user_list)
path
#> [1] "/path/to/all_usersuser_1" "/path/to/all_usersuser_2"

# Note paste0() and file.path recycle the inputs to the length of the longest one
file.path("path", 1:3)  # Don't use "/"
#> [1] "path/1" "path/2" "path/3"
paste0("path/", 1:3)
#> [1] "path/1" "path/2" "path/3"


--

# Not what you want
for (i in user_list) {
  print(i)  # See what's going on
  path <- print(paste0(path_all_users, i))
}
#> [1] "user_1"
#> [1] "/path/to/all_usersuser_1"
#> [1] "user_2"
#> [1] "/path/to/all_usersuser_2"
path
#> [1] "/path/to/all_usersuser_2"

# What you want but complicated
(path <- character(length(user_list)))  # For speed, pre-fill then replace
#> [1] "" ""
for (i in seq_along(user_list)) {
  print(user_list[[i]])  # See what's going on
  path[[i]] <- print(paste0(path_all_users, user_list[[i]]))
}
#> [1] "user_1"
#> [1] "/path/to/all_usersuser_1"
#> [1] "user_2"
#> [1] "/path/to/all_usersuser_2"
path
#> [1] "/path/to/all_usersuser_1" "/path/to/all_usersuser_2"

Created on 2021-09-14 by the reprex package (v2.0.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment