首页 > 解决方案 > 如果数字在 750 和 850 之间,则删除列表的元素

问题描述

想用for循环解决

x = list(20000,45,443,"Texas",680,410,"Chennai",121,799,190,810) 

 `  for (i in seq(x)){
  if(x[[i]]>750 & x[[i]]<850){
    x[[i]] <- NA }}`

标签: rfor-loop

解决方案


我们可以用Filter

Filter(function(x) !(is.numeric(x) & x > 750 & x < 850), num_list)

#[[1]]
#[1] 20000

#[[2]]
#[1] 45

#[[3]]
#[1] 443

#[[4]]
#[1] "Texas"

#[[5]]
#[1] 680

#[[6]]
#[1] 410

#[[7]]
#[1] "Chennai"

#[[8]]
#[1] 121

#[[9]]
#[1] 190

以下是相同逻辑的更多变体。

num_list[sapply(num_list, function(x) !(is.numeric(x) & x > 750 & x < 850))]
purrr::discard(num_list, ~is.numeric(.x) & .x > 750 & .x < 850)
purrr::keep(num_list,~!(is.numeric(.x) & .x > 750 & .x < 850))

如果您必须使用for循环,这是一种方法

index <- numeric()
for(i in seq_along(num_list)) {
   if(is.numeric(num_list[[i]]) & num_list[[i]] > 750 & num_list[[i]] < 850)
    index <- c(index, i)
}
num_list[index] <- NULL

数据

num_list = list(20000,45,443,"Texas",680,410,"Chennai",121,799,190,810)

推荐阅读