我需要一个带有两个参数的函数:
对于每个给定的年龄,该函数应返回相应的年龄组。
我很快就想出了这个带有两个嵌套循环的函数,并且它有效:
classifyAge <- function(ages, intervals) {
result <- character(length(ages))
for (i in seq_along(ages)) {
for (j in seq_along(intervals)) {
range <- as.numeric(strsplit(intervals[j], "-")[[1]])
if (ages[i] >= range[1] & ages[i] <= range[2]) {
result[i] <- intervals[j]
break
}
}
}
return(result)
}
result <- classifyAge(c(1, 2, 3, 5, 5, 7,0), c("1-2", "3-4", "5-Inf"))
print(result)
[1] "1-2" "1-2" "3-4" "5-Inf" "5-Inf" "5-Inf" ""
我只是想知道是否可以使用向量化函数以某种方式实现相同的功能?
我知道“剪切”功能,但我没有成功使用它。
cut
是推荐和首选。
vec <- c(1, 2, 3, 5, 5, 7,0)
bins <- c(0, 2, 4, Inf)
cut(vec, bins, labels = paste(bins[-length(bins)]+1, bins[-1], sep="-"))
# [1] 1-2 1-2 3-4 5-Inf 5-Inf 5-Inf <NA>
# Levels: 1-2 3-4 5-Inf