xmin = as.integer(readline("Input the left boundary of the period: "))
xmax = readline("Input the right boundary of the period: ")
step = readline("Input the step of the sequence: ")
new.function = function(xmin, xmax, step) {
while (xmin<=xmax) {
y = (5 log(xmin) * exp(xmin) * xmin - (1.5/xmin))
print(y)
xmin = as.integer(xmin) as.integer(step)
}
}
v <- unlist(new.function(xmin, xmax, step))
print(v)
I would like to change the answer to vector, which mean showing all answers in one line not in 4 consecutive lines. If I input 1, 4, 1 the answer will be 3.5 to 307.1 from top to bottom. Is it possible to get the answer in one line? (3.5, 14.49341, 70.69865, 307.3814)
CodePudding user response:
Store the results in a vector instead of printing them:
new.function = function(xmin, xmax, step) {
y <- c() ## Add this to your function
while (xmin<=xmax) {
y = c(y, (5 log(xmin) * exp(xmin) * xmin - (1.5/xmin))) # Modify this
xmin = as.integer(xmin) as.integer(step)
}
y
}
v <- new.function(xmin, xmax, step)
v
CodePudding user response:
Slightly different from @onyambu answer, just avoiding a growing vector as pointed out in R inferno
new.function = function(xmin, xmax, step) {
y <- vector(mode="numeric", length=xmax)
i <- 0
while (xmin<=xmax) {
i <- i 1
y[i] <- (5 log(xmin) * exp(xmin) * xmin - (1.5/xmin))
xmin <- as.integer(xmin) as.integer(step)
}
return(y)
}
Example:
> new.function(1,4,1)
[1] 3.50000 14.49341 70.69865 307.38143