使用FOR循环和IF-ELSE创建一个仅包含具有偶数ID的推文的数据框

问题描述 投票:-4回答:2

我需要使用for循环和if else语句删除数据框中数字不均匀的行,但如果符合条件,我不知道如何删除行。

到目前为止我有这个:

for (i in as.integer(substr(My_columns[,6],18,18))){
  if((i %% 2) == 0) {
  }
  else {
  }
r loops rstudio
2个回答
0
投票

另一个,简短而简单。

# removes odd rows
> df[seq(2,nrow(df),2),]

或者使用for循环(仅供参考):

## using a for loop

get_index <- c()
for(i in seq(nrow(df)))
{
    if ( i%%2 == 0)
    {
        get_index <- c(get_index, i)
    }

}
print(df[get_index,])
    a  b
2   2  2
4   4  4
6   6  6
8   8  8
10 10 10
12 12 12
14 14 14
16 16 16
18 18 18
20 20 20

0
投票

这里不需要for循环;你可以使用直接索引:

# Sample data
df <- data.frame(
    a = seq(1:20),
    b = seq(1:20))

# Remove rows with uneven numbers
df[-(2 * seq(0, nrow(df) - 1) + 1), ];
#    a  b
#2   2  2
#4   4  4
#6   6  6
#8   8  8
#10 10 10
#12 12 12
#14 14 14
#16 16 16
#18 18 18
#20 20 20

或者使用模运算符:

# Keep rows with even numbers
df[1:nrow(df) %% 2 == 0, ];    
© www.soinside.com 2019 - 2024. All rights reserved.