R 找出能给出目标平均值的所有数字组合
我有一组数字和一个给定的平均值。我需要找到最有效的方法来找到这些数字的组合,这将给出目标的平均值R 找出能给出目标平均值的所有数字组合,r,combinations,mean,R,Combinations,Mean,我有一组数字和一个给定的平均值。我需要找到最有效的方法来找到这些数字的组合,这将给出目标的平均值 numbers<-c(8.05,7.59,5.52,6.73,8.01,7.44,7.35,7.42,6.05) target_mean<-7.34 数字正如Akrun提到的,精确匹配浮点数并不容易。但是,以下是如何找到平均值高于或低于目标值+/-0.01的组合: target_mean<-7.34 numbers<-c(8.05,7.59,5.52,6.73,8.01,7
numbers<-c(8.05,7.59,5.52,6.73,8.01,7.44,7.35,7.42,6.05)
target_mean<-7.34
数字正如Akrun提到的,精确匹配浮点数并不容易。但是,以下是如何找到平均值高于或低于目标值+/-0.01的组合:
target_mean<-7.34
numbers<-c(8.05,7.59,5.52,6.73,8.01,7.44,7.35,7.42,6.05)
res <- Map(combn, list(numbers), seq_along(numbers), simplify = FALSE)
res2 <- unlist(res, recursive = FALSE)[lapply(unlist(res, recursive = FALSE),mean)<(target_mean+.01)&
lapply(unlist(res, recursive = FALSE),mean)>(target_mean-.01)]
res2
[[1]]
[1] 8.05 7.59 5.52 8.01 7.44 7.42
[[2]]
[1] 8.05 7.59 5.52 8.01 7.44 7.35 7.42
sapply(res2,mean)
[1] 7.33833 7.34000
正如Akrun提到的,精确匹配浮点数并不容易。但是,以下是如何找到平均值高于或低于目标值+/-0.01的组合:
target_mean<-7.34
numbers<-c(8.05,7.59,5.52,6.73,8.01,7.44,7.35,7.42,6.05)
res <- Map(combn, list(numbers), seq_along(numbers), simplify = FALSE)
res2 <- unlist(res, recursive = FALSE)[lapply(unlist(res, recursive = FALSE),mean)<(target_mean+.01)&
lapply(unlist(res, recursive = FALSE),mean)>(target_mean-.01)]
res2
[[1]]
[1] 8.05 7.59 5.52 8.01 7.44 7.42
[[2]]
[1] 8.05 7.59 5.52 8.01 7.44 7.35 7.42
sapply(res2,mean)
[1] 7.33833 7.34000
target\u意思是浮点数比较应该小心浮点数比较应该小心这就是我要找的。谢谢这就是我要找的。谢谢