r - 如果数字在 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 }}`
解决方案
我们可以用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)
推荐阅读
- mysql - 如何在 MySql 中创建超过 100 列的表
- r - R在识别因子方面存在问题
- swift - 完成变异方法后访问结构属性的正确方法是什么?(内存访问冲突)
- rest - Shopify Admin API:无法将资产上传到 Layout 文件夹 - 422 错误
- python - 在 Python 中创建指向 2D 字符数组的指针
- redis - 注册实现实例化或定义空构造函数的自定义序列化程序 - Wildfly 上的 Redis 缓存
- windows-10 - 带有跟踪标志的 IISExpress 不提供任何附加信息,并且仍然提示使用跟踪标志运行
- makefile - 如何在 makefile 中为 grep 命令添加引号?
- reactjs - Azure DevOps docker build 与本地构建产生不同的结果
- optimization - 约束规划与线性规划:解决方案的速度和质量