-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulti-assignment.R
86 lines (52 loc) · 1.66 KB
/
multi-assignment.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
`:=` <- function(lhs, rhs) {
LHS <- as.character(substitute(lhs))[-1L]
is_matrix <- is.matrix(rhs)
is_list <- is.list(rhs)
is_vector <- is.vector(rhs)
if (length(LHS) == 1) {
assign(x = LHS, value = rhs, envir = parent.frame())
} else {
if (length(LHS) <= length(rhs)) {
for (i in seq_along(LHS)) {
if (is_valid_variable_name(LHS[i])) {
if (is_list)
assign(x = LHS[i], value = rhs[[i]], envir = parent.frame())
if (is_matrix)
assign(x = LHS[i], value = rhs[, i], envir = parent.frame())
if (is_vector & !is_list)
assign(x = LHS[i], value = rhs[i], envir = parent.frame())
}
}
}
}
}
conc <- function(lhs, rhs) {
LHS <- as.character(substitute(lhs))
is_matrix <- is.matrix(rhs)
is_df <- is.data.frame(rhs)
is_list <- is.list(rhs)
is_vector <- is.vector(rhs)
tmp <- get(x = LHS, envir = parent.frame())
if (is_df | is_matrix) {
assign(x = LHS, value = cbind(tmp, rhs), envir = parent.frame())
}
if (is_list) {
assign(x = LHS, value = c(tmp, rhs), envir = parent.frame())
}
}
# https://www.r-bloggers.com/testing-for-valid-variable-names/
is_valid_variable_name <- function(x, allow_reserved = TRUE, unique = FALSE) {
ok <- rep.int(TRUE, length(x))
#is name too long?
max_name_length <- if(getRversion() < "2.13.0") 256L else 10000L
#is it a reserved variable, i.e.
#an ellipsis or two dots then a number?
if(!allow_reserved)
{
ok[x == "..."] <- FALSE
ok[grepl("^\\.{2}[[:digit:]]+$", x)] <- FALSE
}
#are names valid (and maybe unique)
ok[x != make.names(x, unique = unique)] <- FALSE
ok
}