Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing elements of arrays within a list (R)

Tags:

r

Okay, here's the situation: I have the following list of arrays:

N <- c('A', 'B', 'C')
ll <- sapply(N, function(x) NULL)
ll <- lapply(ll, function(x) assign("x", array(0, dim = c(2,2)))) .

Now I want to replace, say, the element at position [1,1] in those arrays by a given quantity, say 10. What I'm doing, following this question here. That is, I'm doing the following:

x <- lapply(ll, function(x) {x[1,1] <- 10}),

which should make x a list of three 2x2 arrays with the [1,1] element equal to 10, all others equal to 0. Instead of that, I'm seeing this:

> x <- lapply(ll, function(x) {x[2,1] <- 10})
> x
$A
[1] 10

$B
[1] 10

$C
[1] 10

Any ideas of what's going on here?

like image 688
Jose L. Lykón Avatar asked Jan 31 '26 04:01

Jose L. Lykón


1 Answers

You're not returning the whole vector. So, the last argument is returned. That is, when you do,

x <- lapply(ll, function(x) {x[2,1] <- 10})

You intend to say:

x <- lapply(ll, function(x) {x[2,1] <- 10; return(x)})

If you don't specify a return value, the last assigned value is returned by default which is 10. Instead you should use return(x) or equivalently just x as follows:

x <- lapply(ll, function(x) {x[2,1] <- 10; x})
# $A
#      [,1] [,2]
# [1,]    0    0
# [2,]   10    0
# 
# $B
#      [,1] [,2]
# [1,]    0    0
# [2,]   10    0
# 
# $C
#      [,1] [,2]
# [1,]    0    0
# [2,]   10    0
like image 98
Arun Avatar answered Feb 01 '26 18:02

Arun