我试图在循环中按名称删除变量时遇到困难,发现用Magrittr管道执行此操作是不可能的(?):
eg.names <- unlist(lapply(0:4, function(x){
eg <- paste0('example.var.',as.character(x))
}))
for (examplename in eg.names) {
assign(examplename, 10)
}
library('magrittr')
for (examplename in eg.names) {
examplename %>%
rm(list = as.character(.))
print(exists(examplename))
}
### Gives:
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# Warning messages:
# 1: In rm(list = .) : object 'example.var.0' not found
# 2: In rm(list = .) : object 'example.var.1' not found
# 3: In rm(list = .) : object 'example.var.2' not found
# 4: In rm(list = .) : object 'example.var.3' not found
# 5: In rm(list = .) : object 'example.var.4' not found
### Piping `examplename` to `rm(list = as.character(.))` also doesn't work...
### Working non-%>% version:
for (examplename in eg.names) {
rm(list = as.character(examplename))
}
在这里我是否应该避免在Magrittr中做些什么,或者实际上是否有某种方法呢?
答案 0 :(得分:1)
这很好用:
for (examplename in eg.names) {
examplename %>%
rm(list = .,envir=globalenv())
print(exists(examplename))
}
# [1] FALSE
# [1] FALSE
# [1] FALSE
# [1] FALSE
# [1] FALSE