Last active
August 29, 2015 14:11
-
-
Save leoluyi/a8615081c0125544feeb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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