Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中打印for循环中的列数_R_For Loop - Fatal编程技术网

在R中打印for循环中的列数

在R中打印for循环中的列数,r,for-loop,R,For Loop,我可能有一个最愚蠢的问题,所以请容忍我。我想了解R中for循环的逻辑 df = matrix(c(1,2,3,4,5,6,7,8,9),3,3) #create a 3x3 matrix for ( i in 1:ncol(df)){ print(i) } # [1] 1 # [1] 2 # [1] 3 为什么只打印第一列结果,不应该按如下方式打印所有列元素: # [1] 1 # [1] 2 # [1] 3 # [2] 4 # [2] 5 #

我可能有一个最愚蠢的问题,所以请容忍我。我想了解R中for循环的逻辑

  df = matrix(c(1,2,3,4,5,6,7,8,9),3,3) #create a 3x3 matrix

  for ( i in 1:ncol(df)){
       print(i)
   }

#  [1] 1
#  [1] 2
#  [1] 3
为什么只打印第一列结果,不应该按如下方式打印所有列元素:

#  [1] 1 
#  [1] 2
#  [1] 3
#  [2] 4 
#  [2] 5
#  [2] 6
#  [3] 7 
#  [3] 8
#  [3] 9

谢谢你的帮助,请保持你的答案在一个虚拟的水平。

好吧,除了打字错误。。。你应该知道ncol(df)=3,对吧?因此,当您使用循环时:

for ( i in 1:ncol(df))
i
将仅为1、2、3

你是。。。对
[1]
感到困惑??表示打印的第一行,但不表示矩阵的第一列。也许你应该试试更随机的矩阵:

df <- matrix(runif(9), 3, 3)

df我想你是想这样做的:
matrix(c(1,2,3,4,5,6,7,8,9),nrow=3,ncol=3)
在for循环中,你要打印的只是变量
I
try
print(df[,I])
,它访问矩阵的列。