对 vector 的每个唯一元素使用 approxfun
Use approxfun with each unique element of vector
我是 R 的新手,我想了解使用 "apply" 系列函数来避免循环和自定义函数的概念。不幸的是,我在第一次练习中就失败了。
这是我的最小可重现示例:
x <- data.frame(Hours=cbind(c(rep(5,5),rep(6,5),rep(7,5),rep(8,5),rep(9,5))),Price=c(cbind(seq(48,50.4, by=0.1),seq(48,52.8, by=0.2),seq(48,55.2, by=0.3),seq(48,57.8, by=0.4),seq(48,60.0, by=0.5))),Volume=seq(10000:10024))
f1 <- approxfun(x$Volume,x$Price, rule=2)
plot(x$Volume, x$Price)
curve(f1, add=TRUE)
但是,我想在 x$Hour
中的每个唯一小时执行 approxfun()
。
我该如何处理?
感谢您的帮助。
此解决方案由 bunk 提供。
成语是split/apply/combine:拆分数据,应用函数,合并结果。 R/*plyr/data.table etc 有很多函数可以做到这一点:
fns <- lapply(split(x, x$Hours), function(dat) approxfun(dat$Volume, dat$Price, rule=2)); plot(x$Volume, x$Price); cols <- 1; for(fn in fns) curve(fn, add=TRUE, col=(cols<<-cols+1))
我是 R 的新手,我想了解使用 "apply" 系列函数来避免循环和自定义函数的概念。不幸的是,我在第一次练习中就失败了。
这是我的最小可重现示例:
x <- data.frame(Hours=cbind(c(rep(5,5),rep(6,5),rep(7,5),rep(8,5),rep(9,5))),Price=c(cbind(seq(48,50.4, by=0.1),seq(48,52.8, by=0.2),seq(48,55.2, by=0.3),seq(48,57.8, by=0.4),seq(48,60.0, by=0.5))),Volume=seq(10000:10024))
f1 <- approxfun(x$Volume,x$Price, rule=2)
plot(x$Volume, x$Price)
curve(f1, add=TRUE)
但是,我想在 x$Hour
中的每个唯一小时执行 approxfun()
。
我该如何处理?
感谢您的帮助。
此解决方案由 bunk 提供。
成语是split/apply/combine:拆分数据,应用函数,合并结果。 R/*plyr/data.table etc 有很多函数可以做到这一点:
fns <- lapply(split(x, x$Hours), function(dat) approxfun(dat$Volume, dat$Price, rule=2)); plot(x$Volume, x$Price); cols <- 1; for(fn in fns) curve(fn, add=TRUE, col=(cols<<-cols+1))