1

Here is my code:

get_test <- function(name){
  data <- filter(data_all_country,country == name)
  # transform the data to a time series using `ts` in `stats`
  data <- ts(data$investment, start = 1950)
  data <- log(data)
  rule <- substitute(name)
  assign(rule,data)
}

As in the code, I try to build a function by which I could input a country's name given in character string, and then the variable named by the country would be generated automatically. However, I run this code, and it runs but with no exact variable generated as I want. For example, I want to have a variable called Albania in the environment after I code get_test("Albania").

I wonder why?

Ps: And the dataset of data_all_country is as following:

    year country investment
1 1950 Albania         NA
2 1951 Albania         NA
3 1952 Albania         NA
4 1953 Albania         NA
5 1954 Albania         NA
6 1955 Albania         NA

Note that the dataset is OK, just some of it is NA

4
  • Your description makes no mention of ts(). Reduce your example to the essentials. Also show the code that calls the fn. Commented Nov 30, 2017 at 5:59
  • Hi, @42 , ts is a function to transform into the time series. Commented Nov 30, 2017 at 6:04
  • may be it is ts(data$data_all_country.investment, start = 1950) Commented Nov 30, 2017 at 6:18
  • Sorry for the misunderstanding, the dataset is an example using the function data.frame() to avoid so many unnecessary columns, the $ part is of no problem. Commented Nov 30, 2017 at 6:22

1 Answer 1

3

I think you have to specify the environment for assign, else it will use the current environment (in this case within the function).

You could use

assign(name, data, envir = .GlobalEnv)

or

assign(name, data, pos = 1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.