我有
txt <- "{a} is to {b} what {c} is to {d}"
key <- c(a='apple', b='banana', c='chair', d='door')
fun <- function(x) key[x]
Run Code Online (Sandbox Code Playgroud)
我想快速转换txt为key:
"apple is to banana what chair is to door"
Run Code Online (Sandbox Code Playgroud)
我知道我可以gsub像这样重复使用(或类似的东西):
for (v in names(key)) txt <- gsub(sprintf('{%s}',v), fun(v), txt, fixed = TRUE)
txt
# [1] "apple is to banana what chair is to door"
Run Code Online (Sandbox Code Playgroud)
但我的txt和key都很长,所以上面是有问题的。我想知道是否有更快的方法,例如:
gsub(sprintf('{%s}',names(key)), key, fixed = TRUE) # Does not work
gsub('\\{(a|b|c|d)\\}', fun(...), txt, …Run Code Online (Sandbox Code Playgroud) 我可以制作一个包含函数的列表,例如,
foo <- list(value=1, func=function(x) x+1)
Run Code Online (Sandbox Code Playgroud)
然后foo$func(3)给出4. 但是该函数是否可以$func访问$value同一列表中的元素?我尝试过以下方法,(显然)是错误的:
foo <- list(value=1, func=function(x) x+value)
foo$func(3)
# Error in foo$func(3) : object 'value' not found
Run Code Online (Sandbox Code Playgroud)
我知道以下代码可以工作:
bar <- list(value=1, func=function(FOO,x) x+FOO$value)
bar$func(bar, 3)
# [1] 4
func <- function(FOO,x) x+FOO$value
func(foo,3)
# [1] 4
Run Code Online (Sandbox Code Playgroud)
但由于某些原因,我想使用foo$func(3)语法而不是func(foo,3)。R可以实现这个功能吗?
谢谢。
编辑
除了下面有用的答案之外,?ReferenceClasses也很有用。
我可以通过类似的方法将数据框中的一列的匹配副本复制到另一个数据框中
DF2$y <- DF1[match(DF2$id2, DF1$id1), "z"] # DF1 and DF2 are data frames
Run Code Online (Sandbox Code Playgroud)
其中DF2$id2与 匹配DF1$id1。我想知道我可以用数据表来进行这种操作。我的数据表有数百万行和数百列。我已经完成了setkey(DT1, id1)并且setkey(DT2, id2).
这有效:
DT2[, y := DT1[match(DT2$id2, DT1$id1), "z"]] # DT1 and DT2 are data tables
Run Code Online (Sandbox Code Playgroud)
但我担心这match部分可能会花费比必要的时间更长的时间。(或者这是不可避免的?)
据我所知,我还可以使用列选择、merge和重命名:
tmp <- DT1[, c("id1", "z")] # column selection
DT3 <- merge(DT2, tmp, by.x = "id2", by.y = "id1", all.x = TRUE, suffixes = c("", ".y")) # merge
setnames(DT3, "z.y", "y") # rename
Run Code Online (Sandbox Code Playgroud)
(前两行可以写在一行上)但这似乎有点太复杂了。有没有更简单、快速的解决方案? …
它需要(在我的MBP上使用2.9 GHz Intel Core i7和16 GB内存)超过20秒才能获得40,000 x 1,000矩阵的交叉产品:
> system.time(a <- crossprod(matrix(pi,40000,1000)))
user system elapsed
23.808 0.139 24.001
Run Code Online (Sandbox Code Playgroud)
有没有办法让它更快?谢谢你的帮助.