Syed Riaz Mahmood Ali
Syed Riaz Mahmood Ali

Reputation: 105

Create a new dataframe by using other dataframe's column

I have a 496 dataframes of S&P 500 stocks. each dataframe have diffrent name and column name like these

         AAL.Open  AAL.High  AAL.Low AAL.Close   AAL.Volume
09-12-13    23.85   25.44   23.45      24.6        43197268
10-12-13    24.5    25.17   24.41      24.88       18660625

         AA.Open  AA.High   AA.Low  AA.Close    AA.Volume
09-12-13    22.5    24.25   20.13     21           6639
10-12-13    21.2    21.2    20.89     21           10963

Now I want to cteare a new Dataframe of 496 columns by taking a particular column of each dataframes like this

          AAL.High    AA.High   -----   ------
09-12-13    25.44     24.25
10-12-13    25.17      21.2

Upvotes: 0

Views: 242

Answers (1)

akrun
akrun

Reputation: 887881

We place the datasets in a list and extract the column of interest. Based on the OP's code, the column names are not exact. SO, we could either use grep

do.call(cbind, lapply(lst, function(x) x[grep("High", names(x))]))

or the column position by numeric indexing

do.call(cbind, lapply(lst, function(x) x[2]))

NOTE: Assumed that the datasets are data.frame

data

lst <- list(d1, d2)

Or with dput

lst <- list(structure(list(AAL.Open = c(23.85, 24.5), AAL.High = c(25.44, 
 25.17), AAL.Low = c(23.45, 24.41), AAL.Close = c(24.6, 24.88), 
AAL.Volume = c(43197268L, 18660625L)), .Names = c("AAL.Open", 
 "AAL.High", "AAL.Low", "AAL.Close", "AAL.Volume"), class = "data.frame", 
 row.names = c("09-12-13", 
 "10-12-13")), structure(list(AA.Open = c(22.5, 21.2), AA.High = c(24.25, 
  21.2), AA.Low = c(20.13, 20.89), AA.Close = c(21L, 21L), 
 AA.Volume = c(6639L, 
 10963L)), .Names = c("AA.Open", "AA.High", "AA.Low", "AA.Close", 
 "AA.Volume"), class = "data.frame", row.names = c("09-12-13", 
 "10-12-13")))

Upvotes: 2

Related Questions