0

See below

for(stockName in c("AAPLstock", "FBstock", "GOOGstock", "HPQstock", "MSFTstock", "YHOOstock")){
assign(paste(stockName), read.table(paste(stockName,'.txt', sep = ""), quote="\"", comment.char=""))  }

This creates these variables. Which is all cool

ls(pattern = "stock")
[1] "AAPLstock" "FBstock"   "GOOGstock" "HPQstock"  "MSFTstock"
[6] "stockName" "YHOOstock"

When I try to assign all of them to a data frame like below

df<-list(ls(pattern = "stock"))
> df
[[1]]
[1] "AAPLstock" "FBstock"   "GOOGstock" "HPQstock"  "MSFTstock"
[6] "stockName" "YHOOstock"

What I want is for df to contain these stocks as variables, not as strings. So the function below gives me the desired result

df <- list(AAPLstock, FBstock, GOOGstock, HPQstock, MSFTstock, YHOOstock)

But that requires me to type out all the variables. The thing is, I am going to be doing that but with more stocks, and I don't want to type the name of a 100 variables, and it's going to be a pain to change. So I want a way to assign strings that represent variables to a data frame using ls() or something similar.

I have tried Parse and assign, but they still assigned df strings rather than variables.

3
  • Why not skip using assign altogether, and create a named list using lapply over your vector of stocknames? Commented Apr 30, 2016 at 7:26
  • @Heroka how would I do that? Commented Apr 30, 2016 at 7:32
  • 1
    lapply(stockNameVector, function(stockName) read.table(paste(... ) Commented Apr 30, 2016 at 7:41

1 Answer 1

1

Consider using mget() to pull multiple variables by string reference.

df <- data.frame(mget(ls(pattern = "stock")), stringsAsFactors =  FALSE)

But as mentioned also consider building a running list of stocks and rbind to a dataframe:

stockName <- c("AAPLstock", "FBstock", "GOOGstock", "HPQstock", "MSFTstock", "YHOOstock")
listOfStocks <- lapply(stockName, 
                       function(s) { 
                             read.table(paste(s,'.txt', sep = ""), 
                                        quote="\"", comment.char="")
                       })
df <- do.call(rbind, listOfStocks)
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.