R 中范围的 for 循环(包括示例)
您可以使用以下基本语法在 R 中编写带有范围的 for 循环:
for (i in 1:10) { do something }
以下示例展示了如何在实践中使用此语法。
示例1:打印范围内的值
下面的代码展示了如何使用for循环打印某个范围内的每个值:
#print every value in range of 1 to 10 for (i in 1:10) { print(i) } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7 [1] 8 [1] 9 [1] 10
示例2:对范围内的值执行操作
下面的代码展示了如何使用for循环对一定范围内的每个值执行特定的操作:
#definevector x <- c(4, 7, 9, 12, 14, 16, 19) #print square root of every value in vector for (i in 1: length (x)) { print(paste(' The square root of the value in position ', i, ' is ', sqrt(x[i]))) } [1] "The square root of the value in position 1 is 2" [1] "The square root of the value in position 2 is 2.64575131106459" [1] "The square root of the value in position 3 is 3" [1] "The square root of the value in position 4 is 3.46410161513775" [1] "The square root of the value in position 5 is 3.74165738677394" [1] "The square root of the value in position 6 is 4" [1] "The square root of the value in position 7 is 4.35889894354067"
示例3:对数据框中的值进行操作
以下代码展示了如何使用for循环对r中数据帧的特定列的每个值执行特定操作:
#define data frame
df <- data. frame (a=c(3, 4, 4, 5, 8),
b=c(8, 8, 7, 8, 12),
c=c(11, 15, 19, 15, 11))
#view data frame
df
ABC
1 3 8 11
2 4 8 15
3 4 7 19
4 5 8 15
5 8 12 11
#multiply every value in column 'a' by 2
for (i in 1: length (df$a)) {
df$a[i] = df$a[i]*2
}
#view updated data frame
df
ABC
1 6 8 11
2 8 8 15
3 8 7 19
4 10 8 15
5 16 12 11