R中的图案绘制
每个人都找到了一种用其他编程语言打印图案的简单方法。但使用 R 语言是一项艰巨的任务。本文重点介绍使用 R 语言及其构造绘制各种模式。
方法
- 开始第一个循环的行数
- 启动要显示的项目的第二个循环
- 打印项目
- 增加第二个循环直到达到条件
- 递增第一个循环直到条件为真
- 以这种方式继续
程序一:用数字画一个三角形
R
stars = c()
for(i in 1:5){
for(j in 1:i+1){
stars = c(stars, i)
}
print(stars)
stars = c()
}
R
#creating a empty list to store
stars = c()
for(i in 1:5){
for(j in 1:i+1){
stars = c(stars, "*")
}
# line by line printing
print(stars)
stars = c()
}
R
starsrev = c()
i=1
j=5
while(i<=5){
for(j in 1:j){
starsrev = c(starsrev, "*")
}
print(starsrev)
starsrev = c()
i=i+1
j=j-1
}
R
i=1
stars = c()
while(i<=5){
for(j in 1:i+1){
stars = c(stars, "*")
}
print(stars)
stars = c()
i=i+1
}
starsrev = c()
i=1
j=5
while(i<=5){
for(j in 1:j){
starsrev = c(starsrev, "*")
}
print(starsrev)
starsrev = c()
i=i+1
j=j-1
}
输出:
[1] 1
[1] 2 2
[1] 3 3 3
[1] 4 4 4 4
[1] 5 5 5 5 5
程序2:用*画一个三角形
电阻
#creating a empty list to store
stars = c()
for(i in 1:5){
for(j in 1:i+1){
stars = c(stars, "*")
}
# line by line printing
print(stars)
stars = c()
}
输出:
[1] "*"
[1] "*" "*"
[1] "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*" "*" "*"
程序三:画倒三角形
电阻
starsrev = c()
i=1
j=5
while(i<=5){
for(j in 1:j){
starsrev = c(starsrev, "*")
}
print(starsrev)
starsrev = c()
i=i+1
j=j-1
}
输出:
[1] "*" "*" "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*"
[1] "*" "*"
[1] "*"
程序4:绘制倒三角形和正常三角形图案
电阻
i=1
stars = c()
while(i<=5){
for(j in 1:i+1){
stars = c(stars, "*")
}
print(stars)
stars = c()
i=i+1
}
starsrev = c()
i=1
j=5
while(i<=5){
for(j in 1:j){
starsrev = c(starsrev, "*")
}
print(starsrev)
starsrev = c()
i=i+1
j=j-1
}
输出:
[1] "*"
[1] "*" "*"
[1] "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*" "*" "*"
[1] "*" "*" "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*"
[1] "*" "*"
[1] "*"