【发布时间】:2015-02-28 03:10:46
【问题描述】:
请参阅下面的代码,其中我从数据框中删除了某些列,并使用名为“col”的变量跟踪我所在的当前列。
问题 如果我从数据框中删除一列,我会减少“col”的值,但是,这似乎没有显示效果。在打印日志时,我看到循环开始时 col 的值似乎没有反映变量 'col' 的递减
数据
col1 = c(1,2,3,4,NA)
col2 = c(2,3,NA,NA,NA)
col3 = c(NA,NA,NA,1,NA)
col4 = c(NA,NA,NA,NA,NA)
col5 = c(1,NA,NA,NA,NA)
col6 = c(NA,NA,NA,NA,1)
col7 = c(NA,NA,NA,NA,2)
col8 = c(NA,NA,NA,NA,8)
col9 = c(NA,NA,NA,NA,NA)
col10= c(1,2,3,4,5)
df = data.frame(col1,col2,col3,col4,col5,col6,col7,col8,col9,col10)
代码
col = 0
totalcolumns = ncol(df)
for (col in 1:totalcolumns)
{
cat(paste("value of col at the start of the loop==",col,"\n",sep=""))
if(length(which(is.na(df[,col]))) == nrow(df))
{
cat(paste("all nas at col==",col,"\n",sep=""))
cat(paste("removing column",col,"\n",sep=""))
df[,col] = NULL
col = col - 1
totalcolumns = totalcolumns - 1
cat(paste("totalcolumns ==",totalcolumns," col==",col, "\n",sep=""))
}
cat(paste("value of col at the end of the loop==",col,"\n\n",sep=""))
}
输出
value of col at the start of the loop==1
value of col at the end of the loop==1
value of col at the start of the loop==2
value of col at the end of the loop==2
value of col at the start of the loop==3
value of col at the end of the loop==3
value of col at the start of the loop==4
all nas at col==4
removing column4
totalcolumns ==9 col==3
value of col at the end of the loop==3
value of col at the start of the loop==5
value of col at the end of the loop==5
value of col at the start of the loop==6
value of col at the end of the loop==6
value of col at the start of the loop==7
value of col at the end of the loop==7
value of col at the start of the loop==8
all nas at col==8
removing column8
totalcolumns ==8 col==7
value of col at the end of the loop==7
value of col at the start of the loop==9
Error in `[.data.frame`(df, , col) : undefined columns selected
请注意,循环第四次迭代结束时 'col' 的值为 3,但在第五次迭代开始时,它显示为 5,而我希望它显示为 4
编辑: 正如 Buckminster 和 MrFlick 所说,在 for 循环中减少 'col' 的值并没有显示出 R 设计的任何效果。但这是一件好事吗?请参阅下面的 C 和 R 之间的区别
R 代码
> for(i in 1:9){print(i);if(i==9){i=i-1}}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
C 代码
#include <stdio.h>
int main(void)
{
int i = 0;
for(i=0;i<10;i++)
{
printf("value of i==[%d]\n",i);
if(i == 9)
{
i--;
}
}
return 0;
}
输出
Will never terminate
1
2
3
4
5
6
7
9
9
...
infinitely printing
9
..
【问题讨论】: