Associative array/Creation: Difference between revisions

add vector example
m (→‎version 2: corrected spelling of "capital". -- ~~~~)
(add vector example)
Line 1,235:
 
=={{header|R}}==
The R object which is the most similar to an associative array is called list; a list can take labels (tags)
<lang R>a <- list(a=1, b=2, c=3.14, d="xyz")</lang>
 
R lacks a native representation of key-value pairs, but different structures allow named elements, which provide similar functionality.
If tags are omitted, numerical tags in increasing order (from 1) are assigned.
 
=== vector example ===
<lang R>print(a$a) # [1] 1
print(a$d) # [1] "xyz"</lang>
 
<lang r>> x <- c(hello=1, world=2, "!"=3)
But we can always access the element of a list with its numeric index, or take directly the value:
<lang R> print(a[4]x)</lang>
<pre>hello world !
1 2 3</pre>
<lang Rr>> print(a[[4]]names(x))</lang>
<pre>[1] "hello" "world" "!"</pre>
<lang Rr>print(a$aunname(x) # [1] 1)</lang>
<pre>[1] 1 2 3</pre>
 
=== list example ===
<lang R>print(a[4])</lang>
 
<lang R>> a <- list(a=1, b=2, c=3.14, d="xyz")</lang>
outputs:
> print(a$d) # [1] "xyz"</lang>
<pre>$da
[1] 1
 
$b
<pre>$d
[1] "xyz"</pre>2
 
$c
while
[1] 3.14
 
$d
<lang R>print(a[[4]])</lang>
[1] "xyz"</pre>
<lang r>> print(names(a))</lang>
<pre>[1] "a" "b" "c" "d"</pre>
<lang r>> print(unname(a))</lang>
<pre>[[1]]
[1] 1
 
[[2]]
outputs <tt>"xyz"</tt>
[1] 2
 
[[3]]
[1] 3.14
 
[[4]]
[1] "xyz"</pre>
 
=={{header|Raven}}==
Anonymous user