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

如何在R中筛选Kennziffer前两位为1-10的数据行

Solution for Filtering Kennziffer Rows

Since Kennziffer is a 4/5-character string, you need to target its first two characters to check if their numeric value falls between 1 and 10. Here's a tidyverse-compatible solution:

library(tidyverse)

new_object <- table_name %>%
  filter(between(as.numeric(str_sub(Kennziffer, 1, 2)), 1, 10))

Key Details:

  • str_sub(Kennziffer, 1, 2): Pulls the first 2 characters from each Kennziffer entry.
  • as.numeric(...): Converts those two characters to a numeric value (e.g., "07" becomes 7, "10" becomes 10).
  • between(..., 1, 10): Filters rows where the converted value is between 1 and 10 (inclusive).

Fixes to Your Original Code:

  • You don’t need to repeat table_name inside filter() when using the pipe (%>%)—the pipe automatically passes the data frame to the next function.
  • Using == with multiple values fails because you’re comparing full strings, not just the first two characters.

Alternative Regex Approach:
If you prefer using regular expressions, this works too:

new_object <- table_name %>%
  filter(str_detect(Kennziffer, "^(0[1-9]|10)"))

This regex matches strings starting with 01-09 or 10, covering all cases where the first two digits equal 1-10.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:00:57