如何在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 eachKennzifferentry.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_nameinsidefilter()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
相关产品推荐
相关产品推荐

