[R] [FORGED] Not seeing the results of a function
Rolf Turner
r@turner @end|ng |rom @uck|@nd@@c@nz
Tue Mar 31 00:42:18 CEST 2020
On 30/03/20 7:55 am, David wrote:
> I’m trying to write a function that will add items to two vectors, and
> then to create a third vector that is of the form 1, 2, 3, …, length of
> one of the newly modified vectors. My problem is that what I’ve written
> doesn’t seem to return any of those modifications. How can I get the
> new values to be returned? Here’s the function below. I want to add a
> value, stp, to the end of the stpos vector, a value mcp to the end of
> the mcpos vector, and the to create that days vector. When I call this
> function with numerical values for stp and mcp, and then ask to see
> stpos, mcpos, and days, nothing has been changed. How can I fix this?
>
> Here’s the function:
> > addday <- function(stp,mcp,stpos,mcpos){stpos<-c(stpos,stp)
> + mcpos<-c(mcpos,mcp)
> + days<-c(1:length(stpos))}
You are probably thinking in terms of "macro languages" rather than in R
terms.
An R function returns, essentially, the last assigned value. So your
function will return the "days" vector; all else disappears into a black
hole in cyberspace.
Something like the following should do what you want:
addday <- function(stp,mcp,stpos,mcpos){
stpos<-c(stpos,stp)
mcpos<-c(mcpos,mcp)
days<-c(1:length(stpos))
rslt <- list(stpos=stpos,mcpos=mcpos,days=days)
rslt
}
As is so often said on this list, you would do well to spend some time
reading and inwardly digesting a basic R tutorial, such as "An
Introduction to R", readily available from the R web page (under "Manuals").
HTH
cheers,
Rolf Turner
--
Honorary Research Fellow
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276
More information about the R-help
mailing list