Home > Mobile >  Using a keyword between list names to apply a function between elements
Using a keyword between list names to apply a function between elements

Time:03-23

I have a list l1 that have file names for each of the list elements. I also have a second list l2, that have some of the same components in the names of the list elements as l1 (i.e., "2013").

I would like to apply the mean function between the list element with the name "C:/Users/2013_mean.csv" and the three elements in l2 based on the keyword "2013". How do I selectively choose that list element, and apply the function between that element and the three elements in l2?

# File List
l1 <- list(2,3)
names(l1) <- c("C:/Users/2013_mean.csv",
               "C:/Users/2013_median.csv")

# Other List
l2 <- list(8,9,10)
names(l2) <- c("2013_A",
               "2013_B",
               "2013_C")

# Attempt to get to the expected
# Look for intersect between the File list names and the Other List names 
set <- intersect(l1[grep("2013", names(l1))], l2)

# Apply function between the list
Map(
  function(i, j) {
    mean(i, j)
  },
  i = a[set],
  j = b[set]
)

This is what I expect to get as the output:

expected <- list(mean(c(l1[[l1]], l2[[1]])),
                 mean(c(l1[[11]], l2[[2]])),
                 mean(c(l1[[l11]], l2[[3]]))
                 )

Any thoughts?

CodePudding user response:

Perhaps we need

lapply(l2, function(x) mean(c(x, l1[[grep("2013_mean", names(l1))]])))
$`2013_A`
[1] 5

$`2013_B`
[1] 5.5

$`2013_C`
[1] 6
  • Related