Add a value to all elements in a list (R)
addition, list, r
Solution
You need double brackets:
a[['bla']]+1
Compare:
R> a["bla"]
$bla
[1] 0 1 2 3
with
R> a[["bla"]]
[1] 0 1 2 3
As Dason points out, the reason you need the double brackets is that when operating on a list the single brackets returns a list containing the elements you asked for whereas the double brackets returns the element itself. You can't use arithmetic operators on lists directly so when you use the single brackets you get a list back and it doesn't know how to 'add 1' to a list.
Other ways of accessing a list element are:
- index: `a[[1]]`
- double: `a$bla`
Problem
I have a list like so: ``` a = list('bla'=c(0,1,2,3)) ``` I want to add 1 to every element so ``` > a['bla'] $bla [1] 1 2 3 4 ``` Of course ``` > a['bla']+1 ``` doesn't work... Help?