我试图在循环中按名称删除变量时卡住了,发现不可能(?)用 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 做的事情,或者实际上有什么方法可以解决吗?