我的问题很简单,但我是 R 新用户......
所以我有一个带有参数的函数。我想将每次调用函数的结果放入一个具有特定名称的向量中。
我的功能
`Window_length<-function(x,y) {
first_interval<-length(which(x <= -1.5))
second_interval<-length(which(x <= -1 & x > -1.5 ))
third_interval<-length(which(x <= -0.5 & x > -1 ))
fourth_interval<-length(which(x <= 0 & x > -0.5 ))
fifth_interval<-length(which(x <= 0.5 & x > 0 ))
sixth_interval<-length(which(x <= 1 & x > 0.5 ))
seventh_interval<-length(which(x <= 1.5 & x > 1 ))
eighth_interval<-length(which(x <= 2 & x > 1.5 ))
ninth_interval<-length(which(x > 2 ))
y <<- c(
rep("1",first_interval),
rep("2",second_interval),
rep("3",third_interval),
rep("4",fourth_interval),
rep("5",fifth_interval),
rep("6",sixth_interval),
rep("7",seventh_interval),
rep("8",eighth_interval),
rep("9",ninth_interval))}`
因此,当我调用 Window_length 时,我想将结果放入给定变量中,例如:
`Window_length(data,output_result)`
在output_result中,我希望有“y”值。
而且我确信我的代码根本不完美。如果有人可以帮助我优化一下我的代码,那就太好了。
我正在尝试制作所有这些,因为我需要用数据 ggplot 绘制一个图。我的值在-4和+3之间。我想创建一个具有特定窗口的绘图 ( <-1.5/-1.5:-1/-1:-0.5/-0.5:0/0:1/1:1.5/1.5:2/>2 )
My data :
data<- c(-3.7865964 -3.7865964 -3.1975372 -3.1975372 -3.169925 -3.1292830 -3.1292830 -2.6629650 -2.4739312 -2.4739312 -2.3536370 -2.3536370 -2.2446224 -2.2446224 -2.0000000 -1.8744691 -1.8744691 -1.7705182 -1.7655347 -1.7655347 -1.7472339 -1.7472339 -1.7062688 -1.7036070........... 1.8744691 1.8744691 2.0000000 2.2446224 2.2446224 2.3536370)
length(data)=21685
To_Be_Plot = data.frame(data,y)
fig1<-ggplot(To_Be_Plot, aes(x=y, y=data))+geom_boxplot()
最佳答案
如果我正确理解了这个问题,一个解决方案是使用函数cut
:
x <- seq(-2.9, 3, l=5000)
FC <- sin(x*pi) + x^2/10 + 0.1*rnorm(5000)
dat <- data.frame(x, FC)
dat$windows <- cut(dat$x, breaks = seq(-3, 3, by=1))
ggplot(data=dat, aes(x, FC, color=windows)) +
geom_boxplot() + theme_bw()
生成的命令绘制箱线图以显示窗口。
关于R 为每次调用函数创建一个向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49733198/