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

R语言:统计data.frame中含指定类型特定值的列数

Ah, I see the issue here! The problem is that R automatically coerces types when using %in%, which is why both columns are being counted even though you’re targeting different value types. Let’s fix this by explicitly checking the column’s data type first before looking for the value.

Solution for Numeric -99

To count only numeric columns that contain the numeric -99, add a check for the column type before verifying the value:

foo <- data.frame(x = c("1", "2", "-99", "4", "5"), y = c(11, 12, -99, -99, 15))

# Count numeric columns with -99
sum(sapply(foo, function(col) is.numeric(col) && (-99 %in% col)))
# Output: 1

Solution for String "-99"

Similarly, to count only character columns with the string "-99", validate the column type first:

# Count character columns with "-99"
sum(sapply(foo, function(col) is.character(col) && ("-99" %in% col)))
# Output: 1

Why This Works

The is.numeric() and is.character() checks ensure we only consider columns of the type we care about. The && operator short-circuits, so if the column isn’t the right type, it won’t even check for the value—this is both clean and efficient.

Reusable Function

If you want a flexible way to handle any target value and type, use this function:

count_type_specific_columns <- function(df, target_value) {
  target_type <- typeof(target_value)
  sum(sapply(df, function(col) {
    typeof(col) == target_type && (target_value %in% col)
  }))
}

# Example usage:
count_type_specific_columns(foo, -99)  # Returns 1 (only numeric column y)
count_type_specific_columns(foo, "-99") # Returns 1 (only character column x)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 15:42:31