Home > front end >  Applying function by pairing by names of a list and file name
Applying function by pairing by names of a list and file name

Time:03-09

I have a list object and a number of ".csv" files that I would like to load in, in order to run the mean function in a very specific manner.

My list l1 contains 5 elements each with a number in it, and my .csv files each when loaded in provided a single number. I would like to pair the .csv files with the elements in the list based on the names(i.e., A,B,C,D,E).

My expected outcome would look something like the expected object created below. Is there a good way of doing this?

l1 <- list(2,3,4,5,6)
names(l1) <- c("A", "B", "C", "D", "E")

# Dummy .csv when loaded in 
A1_csv <- 4
B2_csv <- 6
C3_csv <- 7
D4_csv <- 8
E5_csv <- 9

expected <- list(mean(c(A1_csv, l1[[1]])),
                 mean(c(B2_csv, l1[[2]])),
                 mean(c(C3_csv, l1[[3]])),
                 mean(c(D4_csv, l1[[4]])),
                 mean(c(E5_csv, l1[[5]]))
                 )

CodePudding user response:

For the example data the solution is very straight forward and mentioned already:

a <- as.list(setNames(2:6, letters[1:5]))
b <- c(4, 6:9)
Map(mean, a, b)
#> $a
#> [1] 2
#> 
#> $b
#> [1] 3
#> 
#> $c
#> [1] 4
#> 
#> $d
#> [1] 5
#> 
#> $e
#> [1] 6

Created on 2022-03-07 by the reprex package (v2.0.1)

However, if these list may change a bit and may not contain the same names, then you need something a little more flexible to find the common names and subset the lists first:

a <- as.list(setNames(1:10, letters[1:10]))
b <- as.list(setNames(20:5, letters[20:5]))

set <- intersect(names(a), names(b))

Map(
  function(i, j) {
    mean(i, j)
  },
  i = a[set],
  j = b[set]
)
#> $e
#> [1] 5
#> 
#> $f
#> [1] 6
#> 
#> $g
#> [1] 7
#> 
#> $h
#> [1] 8
#> 
#> $i
#> [1] 9
#> 
#> $j
#> [1] 10

Created on 2022-03-07 by the reprex package (v2.0.1)

  • Related