1

I would like to assign the i-th value of a vector to position [1,1] of the i-th element a list of data.frames.

For example, I'd like to modify 'list1' as follows:

# list of data.frames
list1 <- list(data.frame(v1=c("a","x"),v2=c("x","x")), data.frame(v1=c("b","x"),v2=c("x","x")))
print(list1)

    [[1]]
      v1 v2
    1  a  x
    2  x  x
    
    [[2]]
      v1 v2
    1  b  x
    2  x  x

# vector of new values
new_elements <- c("c", "d")

# desired output
    [[1]]
      v1 v2
    1  c  x
    2  x  x
    
    [[2]]
      v1 v2
    1  d  x
    2  x  x

I have tried an approach similar to this post, without success. My attempt gives a list of the new elements only.

assignNew <- function(x, new, i) {x[[i]][x[[i]][[1, 1]]] <- new[i]}

lapply(seq_along(list1), assignNew, x = list1, new = new_elements) 
xilliam
  • 2,074
  • 2
  • 15
  • 27

2 Answers2

1

You can use Map from base R. This takes any two-parameter function as its first argument, then two objects of the same length as its second and third arguments. It then applies the function to the parallel elements of those objects, returning the result as a list:

Map(function(df, element) {df[1, 1] <- element; df}, list1, new_elements)

#> [[1]]
#>   v1 v2
#> 1  c  x
#> 2  x  x
#> 
#> [[2]]
#>   v1 v2
#> 1  d  x
#> 2  x  x
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

A purrr solution:

library(purrr)
map2(list1, new_elements, function(x, y) {
  x[1, 1] = y
  x
})
# [[1]]
#   v1 v2
# 1  c  x
# 2  x  x

# [[2]]
#   v1 v2
# 1  d  x
# 2  x  x
user63230
  • 4,095
  • 21
  • 43