Sharl
Sharl

Reputation: 175

Changing every element in vector or list by the same number

I have a list (that could be changed to a vector by unlist()) and I want to increment every number by 1.

For example, if I have x <- list(1, 2, 3, 6, 4) I want to end up with a list or a vector that will be 2 3 4 7 5.

I was thinking about using apply or making a function that loops through every element but I feel like that would be messy and there must be an easier way to do it

Upvotes: 0

Views: 75

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

I don't really see how this would be messy. You can add 1 to every element of a list with lapply(). In R, this is the standard method for applying a function over a list.

x <- list(1, 2, 3, 6, 4)
lapply(x, "+", 1) ## for a list result; unlist(x) + 1 for atomic result

Or if you are entering the International Code Golf Championships, you can use

Map("+", x, 1)

Or you can use a for() loop

for(i in seq_along(x)) x[[i]] <- x[[i]] + 1

Or if you have an unlisted list, you can relist it with x as its skeleton.

relist(unlist(x) + 1, x)  ## same as as.list(unlist(x) + 1) here

Upvotes: 4

Related Questions