ShashankAC
ShashankAC

Reputation: 1078

Add a number to a vector inside a list in R

I have a list like this

x <- list(a=1:10, b="Good morning", c="Hi")

If I type x[1] or x[c("a")] I get the numbers 1 to 10 of the vector

I want to add 5 to each element of the vector a inside the list x.

I tried

x[1] + 5 #didn't work

x[c("a")] + 5 #didn't work

I tried a few other things I found on google and they didn't work

Any help will be appreciated.

Upvotes: 1

Views: 1030

Answers (1)

Pere
Pere

Reputation: 746

A few solutions:

> x <- list(a=1:10, b="Good morning", c="Hi")
> x[["a"]] + 5
 [1]  6  7  8  9 10 11 12 13 14 15
> x[[1]] + 5
 [1]  6  7  8  9 10 11 12 13 14 15
> x$a + 5
 [1]  6  7  8  9 10 11 12 13 14 15

The problem with your approach is that [] is the syntax to index vectors, but x is a list and not a vector. To get the an element of a list, you need to use [[]]. By using x[1] you get a sublist whose single element is a vector instead of getting a vector.

Addition in response to comment asking how to update the original list:

In R you can use the same syntax to retrieve values from and object and to assign values to that object.

> x$a <- x$a + 5
> x
$a
 [1]  6  7  8  9 10 11 12 13 14 15

$b
[1] "Good morning"

$c
[1] "Hi"

Any combination of the different possible syntaxes would have worked, too:

x[["a"]] <- x[[1]] + 5

Upvotes: 2

Related Questions