Skip to content

Instantly share code, notes, and snippets.

@leoluyi
Last active August 29, 2015 14:11
Show Gist options
  • Save leoluyi/a8615081c0125544feeb to your computer and use it in GitHub Desktop.
Save leoluyi/a8615081c0125544feeb to your computer and use it in GitHub Desktop.
merge_vars <- function(.data, to, from)
{
to = deparse(substitute(to))
from_vars = substitute(from)
from_var_pos <- setNames(as.list(seq_along(.data)), names(.data))
pos <- eval(from_vars, from_var_pos)
y <- .data[[to]]
# 如果不是NA就填回前面變數
for(i in pos) {
y <- ifelse(!is.na(.data[[i]]) & !identical(.data[[i]], ""),
.data[[i]], y)
}
.data[[to]] <- y
.data
}
# # Examples
#
# df <- data.frame(
# a = c(rep(0, 4), NA),
# b = c(9, 9, NA, 9, NA),
# c = c(NA, NA, 8, NA, NA)
# )
#
# merge_vars(df, a, c(b:c))
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment