1

I have a list of lists like the input example below “testccffilt”. I’m trying to return a list where I pick off the name from each list and the lag. For example, for the first list it would be:

c(‘TimeToShip’,1)

I’ve tried the lapply example below, but it doesn’t give me exactly the output I’m looking for. I have an example of the desired type of output I’m trying to get also below. Any tips are very much appreciated.

input:

> testccffilt

$TimeToShip
           cor lag
3284 0.9998749   1

$TimeToRelease
           cor lag
3285 0.9997293   2

tried:

testlist<-lapply(testccffilt,function(x)list(names(x),x$lag))

testlist

$TimeToShip
$TimeToShip[[1]]
[1] "cor" "lag"

$TimeToShip[[2]]
[1] 1


$TimeToRelease
$TimeToRelease[[1]]
[1] "cor" "lag"

$TimeToRelease[[2]]
[1] 2

desired output:

[[1]]
[1] "TimeToShip" "1"         

[[2]]
[1] "TimeToRelease" "2"     

Data:

dput(testccffilt)
structure(list(TimeToShip = structure(list(cor = 0.999874880882358, 
    lag = 1), .Names = c("cor", "lag"), row.names = 3284L, class = "data.frame"), 
    TimeToRelease = structure(list(cor = 0.999729343078789, lag = 2), .Names = c("cor", 
    "lag"), row.names = 3285L, class = "data.frame")), .Names = c("TimeToShip", 
"TimeToRelease"))
M--
  • 25,431
  • 8
  • 61
  • 93
user3476463
  • 3,967
  • 22
  • 57
  • 117
  • 1
    @markus Thank you for getting back to me so quickly. I added an update to the original post where I dput(testccffilt) – user3476463 Nov 02 '18 at 18:01

1 Answers1

1

Here is one option using a for loop

out <- vector(mode = "list", length(testccffilt))
for (i in 1:length(testccffilt)) {
  out[[i]] <- c(names(testccffilt)[[i]], testccffilt[[i]][["lag"]])
}
out
#[[1]]
#[1] "TimeToShip" "1"         

#[[2]]
#[1] "TimeToRelease" "2" 

Another option is lapply which might be faster.

lapply(1:length(testccffilt), function(x)
  c(names(testccffilt)[[x]], testccffilt[[x]][["lag"]]))
markus
  • 25,843
  • 5
  • 39
  • 58
  • Why not `lapply`? – M-- Nov 02 '18 at 18:13
  • 1
    @Masoud Like so: `lapply(1:length(testccffilt), function(x) c(names(testccffilt)[[x]], testccffilt[[x]][["lag"]]))` ? – markus Nov 02 '18 at 18:15
  • exactly, isn't that faster? – M-- Nov 02 '18 at 18:16
  • @Masoud Dunno. I don't find it any easier to read so I decided in favor of the for loop. Was thinking about `Map` but could not get it working. Would you consider to include a benchmark? – markus Nov 02 '18 at 18:21
  • tbh don't care that much. Just include `lapply` in your answer as well, OP will decide or will benchmark if computation cost is at stake. Cheers. – M-- Nov 02 '18 at 18:24
  • 1
    @markus Thank you, that worked nicely! lists of lists give me such a headache. – user3476463 Nov 02 '18 at 18:33