You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中用str_detect生成二元变量遇报错,求代码修正

你的R代码问题分析及修正方案

第一段代码(ignore_case=T报错)

  • 问题根源是参数名错误或者包未加载:
    • 若用基础R的grepl()函数,大小写忽略的参数名是ignore.case(点分隔),而非ignore_case(下划线分隔),写错参数名会直接报错。正确写法示例:
      df$lonely <- as.integer(grepl("lonely|alone|isolated", df$post, ignore.case = TRUE))
      
    • 若用stringr包的str_detect()函数,参数名确实是ignore_case,但你可能没提前加载stringr包,导致函数无法识别该参数。修正时先加载包再调用函数:
      library(stringr)
      df$lonely <- as.integer(str_detect(df$post, regex("lonely|alone|isolated", ignore_case = TRUE)))
      

第二段代码(提示argument 'no' is missing, with no default)

  • 这个错误是因为使用ifelse()时未写全必填参数。ifelse()必须包含三个参数:判断条件、条件为真的返回值、条件为假的返回值,你大概率漏写了第三个参数(no)。
  • 错误写法示例(缺少no参数):
    df$lonely <- ifelse(grepl("lonely", df$post), 1)
    
  • 修正后的正确写法:
    df$lonely <- ifelse(grepl("lonely|alone|isolated", df$post, ignore.case = TRUE), 1, 0)
    

内容的提问来源于stack exchange,提问作者Buckethead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:50:47