私があなたのために書いたこのヘルパー関数を使用できます:
decisionTree <- function(dataframe, lst) {
if (!is.recursive(lst)) return(lst)
values <- numeric(nrow(dataframe))
indices <- eval(parse(text = names(lst)[1]), dataframe)
values[indices] <- decisionTree(dataframe[indices, ], lst[[1]])
values[!indices] <- decisionTree(dataframe[!indices, ], lst[[2]])
values
}
一般的な形式は、次のような形式で、最初の引数として a を渡しdata.frame
、決定木を表すネストされたリストを 2 番目の引数として渡します。
list("first_variable > 0.3" =
list("second_variable > 0.5" = 1,
"second_variable <= 0.5" = list(
"third_variable > 0.3" = 0,
1) # naming the negated condition is optional
),
"first_variable <= 0.3" = 0)
例
iris$foo <- decisionTree(iris, list("Sepal.Length > 5" = list("Petal.Length > 1.3" = 1, 0), 0))
head(iris) # All entries with Sepal.Length > 5 and Petal.Length > 1.3 will contain a 1.
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species foo
# 1 5.1 3.5 1.4 0.2 setosa 1
# 2 4.9 3.0 1.4 0.2 setosa 0
# 3 4.7 3.2 1.3 0.2 setosa 0
# 4 4.6 3.1 1.5 0.2 setosa 0
# 5 5.0 3.6 1.4 0.2 setosa 0
# 6 5.4 3.9 1.7 0.4 setosa 1
提供したグラフの場合、2 番目の引数は次のようになります。
list("Ts_Armpit > 35.1" = 1,
list("Ts_Breast <= 0.39" = list("Ts_Croup <= 28.9" = 1, 0),
list("Ts_Groin <= 35.1" = 1, list("Ts_Armpit <= 33.7" = 1, 0))))
ここで、1
は不快感を0
示し、快適さを示します。