user42967
user42967

Reputation: 99

Replacing values in a list based on a condition

I have a list of values called squares and would like to replace all values which are 0 to a 40.

I tried:

replace(squares, squares==0, 40)

but the list remains unchanged

Upvotes: 2

Views: 1792

Answers (2)

akrun
akrun

Reputation: 887118

If it is a list, then loop through the list with lapply and use replace

squares <- lapply(squares, function(x) replace(x, x==0, 40))
squares
#[[1]]
#[1] 40  1  2  3  4  5

#[[2]]
#[1] 1 2 3 4 5 6

#[[3]]
#[1] 40  1  2  3

data

squares <- list(0:5, 1:6, 0:3)

Upvotes: 2

Florian
Florian

Reputation: 25385

I think for this purpose, you can just treat it as if it were a vector as follows:

squares=list(2,4,6,0,8,0,10,20)
squares[squares==0]=40

Output:

[[1]]
[1] 2

[[2]]
[1] 4

[[3]]
[1] 6

[[4]]
[1] 40

[[5]]
[1] 8

[[6]]
[1] 40

[[7]]
[1] 10

[[8]]
[1] 20

Upvotes: 1

Related Questions