Reputation: 1061
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
Upvotes: 1
Views: 237
Reputation: 6222
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)
Upvotes: 3