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

