assign函数在循环时候,给变量赋值,算是比较方便
1、给变量赋值
[plain] view plain copy
- for (i in 1:(length(rowSeq)-1)){
- assign(paste("nginx_server_fields7_", i, sep = ""), nginx_server_fields7[(rowSeq[(i-1)+1]):(rowSeq[i+1]), ])
- }
2、通过for循环给变量a1、a2、a3赋值
[plain] view plain copy
- for (i in 1:3){
- assign(paste("a", i, sep = ""), i:10)
- }
- ls()
- [1] "a1" "a2" "a3" "i"
- > a1
- [1] 1 2 3 4 5 6 7 8 9 10
- > a2
- [1] 2 3 4 5 6 7 8 9 10
3、get和assign联合用法
[plain] view plain copy
- rm(list = ls()) #这个命令千万慎重使用
- for(i in 1:3){
- assign(paste("p", i, sep=""), i)
- tmp <- get(paste("p", i, sep=""))
- print(tmp)
- }
- [1] 1
- [1] 2
- [1] 3
- ls()
- [1] "i" "p1" "p2" "p3" "tmp"
时间: 2024-10-05 12:37:56