Skip to content

Instantly share code, notes, and snippets.

@AkselA
Last active August 21, 2018 09:47
Show Gist options
  • Save AkselA/3b4cda6948fa1f367f5637871d691cb4 to your computer and use it in GitHub Desktop.
Save AkselA/3b4cda6948fa1f367f5637871d691cb4 to your computer and use it in GitHub Desktop.
ll <- list(A=1, B=2, C=3)
append(ll, list(X=5:6), after=1) # works
append(ll, list(X=5:6), after="A") # does not work
#EX1
f1 <- function(x) {
x + 1
}
f1(3)
# 4
body(f1)[[2]][[3]] <- 10
f1(3)
# 13
#EX2
f2 <- function(x) {
summary(x)
}
f2(mtcars[1:3])
# mpg cyl disp
# Min. :10.40 Min. :4.000 Min. : 71.1
# 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8
# Median :19.20 Median :6.000 Median :196.3
# Mean :20.09 Mean :6.188 Mean :230.7
# 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0
# Max. :33.90 Max. :8.000 Max. :472.0
body(f2)[[2]]$digits <- 2
f2(mtcars[1:3])
# mpg cyl disp
# Min. :10 Min. :4.0 Min. : 71
# 1st Qu.:15 1st Qu.:4.0 1st Qu.:121
# Median :19 Median :6.0 Median :196
# Mean :20 Mean :6.2 Mean :231
# 3rd Qu.:23 3rd Qu.:8.0 3rd Qu.:326
# Max. :34 Max. :8.0 Max. :472
# from
append <- function (x, values, after = length(x)) {
lengx <- length(x)
if (!after)
c(values, x)
else if (after >= lengx)
c(x, values)
else c(x[1L:after], values, x[(after + 1L):lengx])
}
# to
adjoin <- function (x, values, after = length(x)) {
lengx <- length(x)
if (is.character(after))
after <- which(names(x) == after)
if (!after)
c(values, x)
else if (after >= lengx)
c(x, values)
else c(x[1L:after], values, x[(after + 1L):lengx])
}
adjoin <- append
adjoin.body <- append(as.list(body(append)),
quote(
if (is.character(after))
after <- which(names(x) == after)
),
after=2)
body(adjoin) <- as.call(adjoin.body)
ll <- list(A=1, B=2, C=3)
adjoin(ll, list(X=5:6), after=1)
adjoin(ll, list(X=5:6), after="A")
# both works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment