简体   繁体   中英

Apply pct function across multiple dataframes

First up thanks to who ever takes this question on. I have up to ten data frames that I want to apply the pct function to (from the caroline package). Due to the data I have, which causes an overflow error, I have to divide all the cells by 1000. Once this happens I can apply the pct function without an issue. Then I want to trim off the original data and create a new data frame.

I have managed to write the following function that does the correct thing except it does not save the results (may be it is lacking a return statement). Therefore I could do it long hand. However, that is not the most important thing.

 require (pct)
 finallist <- list(A, B)

 lapply(finallist , function (foo) {

 temp <-  as.data.frame(foo[,1])
 checks <- cbind(temp, foo[,2:480]/1000)
 checka <- pct(checks, tickerlist)
 foo <- checka[c(1, 481:959)]
 })

With the A and B Data frames being formed like this

  A  <- structure(list(mgrname = c("Man A", "Man A", "Man A", "Man B", "Man  B", "Man B", "Man C", "Man C", "Man C"), 
                  ticker = c("AAPL", "MSFT", "TLSA", "AAPL", "MSFT", "TLSA", "AAPL", "MSFT", "TLSA"), 
                  share = c(20L, 30L, 40L, 20L, 10L, 50L, 20L, 20L, 80L)), 
             .Names = c("mgrname", "ticker", "share"), 
             row.names = c(NA, -9L),
             class = "data.frame")

B would be same

The real key is to try and write new data frames out. The code that I started with uses the invisible function (I think it should have an assign function in there somewhere)

  invisible(lapply (names(finalist), 
              function (foo) assign (x = y, value =  temp <-     as.data.frame(foo[,1]),
                 checks <- cbind(temp, foo[,2:480]/1000),
                 checka <- pct(checks, tickerlist),
                 foo <- checka[c(1, 481:959)] , envir =.GlobalEnv)))

But it says

  Error in lapply(names(finalist), function(foo) assign(x = y, value = temp <- as.data.frame(foo[,  : 
   object 'finalist' not found

The final data frame should hopefully look like this

  | mgrname | APPL   | MSFT  | TLSA  |
  |---------|--------|-------|-------|
  | Man A   | .33    |  .5   | .23   |
  | Man B   | .33    |  .16  | .30   |
  | Man C   | .33    |  .33  | .47   |

I found that this code worked.

First do the manipulations

 newlist <- lapply(finallist , function (foo) {
 temp <-  as.data.frame(foo[,1])
 checks <- cbind(temp, foo[,2:4]/100)
 checka <- pct(checks, c("AAPL", "MSFT", "TLSA"))
 foo <- checka[c(1, 5:7)]
 })

Then use this. Namings etc are a bit off but I think I can handle that.

lapply(seq_along(newlist), 
   function(i,x) {assign(paste0("a",i),x[[i]], envir=.GlobalEnv)},
   x=newlist)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM