R语言 图案绘制
每个人都在其他编程语言中找到了一种简单的图案打印方法。但在R语言中,这是一项艰难的任务。本文主要介绍使用R语言及其结构体绘制各种模式。
方法
- 开始第一个循环,计算行数
- 为要显示的项目开始第二个循环
- 打印项目
- 递增第二个循环直到达到一个条件
- 递增第一个循环,直到条件为真
- 继续以这种方式进行
程序1:用数字画一个三角形
stars = c()
for(i in 1:5){
for(j in 1:i+1){
stars = c(stars, i)
}
print(stars)
stars = c()
}
输出
[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] "*" "*" "*" "*" "*"
程序3:绘制倒三角形
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] "*"