web-dev-qa-db-ja.com

Rで辞書/リストを操作する

些細な質問があります:Rに辞書データ構造が見つからなかったので、代わりにリスト(「Word」-> numberなど)を使用しました。そのため、キーのリストを取得する方法に問題があります。誰もが知っていますか?

77
Ivri

はい、list型は適切な近似です。リストでnames()を使用して、「キー」を設定および取得できます。

> foo <- vector(mode="list", length=3)
> names(foo) <- c("tic", "tac", "toe")
> foo[[1]] <- 12; foo[[2]] <- 22; foo[[3]] <- 33
> foo
$tic
[1] 12

$tac
[1] 22

$toe
[1] 33

> names(foo)
[1] "tic" "tac" "toe"
> 
105

「数値」の値がすべて同じモードである場合、リストさえ必要ありません。 Dirk Eddelbuettelの例を取り上げると:

> foo <- c(12, 22, 33)
> names(foo) <- c("tic", "tac", "toe")
> foo
tic tac toe
 12  22  33
> names(foo)
[1] "tic" "tac" "toe"

リストが必要なのは、値が混合モード(文字と数字など)またはベクトルの場合のみです。

リストとベクターの両方で、個々の要素を名前でサブセット化できます:

> foo["tac"]
tac 
 22 

またはリストの場合:

> foo[["tac"]]
[1] 22
49
Calimo

Calimoの少しの答えを拡張するために、この疑似辞書をRで作成するときに役立つと思われるものをいくつか紹介します。

a)辞書のすべての値を返す方法:

>as.numeric(foo)
[1] 12 22 33

b)辞書にキーが含まれているかどうかを確認します。

>'tic' %in% names(foo)
[1] TRUE

c)新しいキーと値のペアを辞書に追加する方法:

c(foo,tic2=44)

結果:

tic       tac       toe     tic2
12        22        33        44 

d)REAL DICTIONARYの要件を満たす方法-キーは繰り返せない(一意のキー) b)とc)を組み合わせて、そのようなキーがあるかどうかを検証する機能を構築し、必要なことを実行する必要があります:たとえば、挿入を許可しない、新しいものが古いものと異なる場合は値を更新する、何らかの方法でキーを再構築する(たとえばそれにユニークな数が追加されます)

e)辞書からキーでペアを削除する方法:

foo <-foo [which(foo!= foo [["tac"]])]

15
andilabs

そもそも辞書を使用する理由はパフォーマンスです。タスクに名前付きベクトルとリストを使用できるのは正しいことですが、問題は、それらが非常に遅くなり、より多くのデータでメモリを消費することです。

しかし、多くの人が知らないことは、R 実際にある組み込みの辞書データ構造:オプションhash = TRUEのある環境

動作させる方法については、次の例を参照してください。

# vectorize assign, get and exists for convenience
assign_hash <- Vectorize(assign, vectorize.args = c("x", "value"))
get_hash <- Vectorize(get, vectorize.args = "x")
exists_hash <- Vectorize(exists, vectorize.args = "x")

# keys and values
key<- c("tic", "tac", "toe")
value <- c(1, 22, 333)

# initialize hash
hash = new.env(hash = TRUE, parent = emptyenv(), size = 100L)
# assign values to keys
assign_hash(key, value, hash)
## tic tac toe 
##   1  22 333
# get values for keys
get_hash(c("toe", "tic"), hash)
## toe tic 
## 333   1
# alternatively:
mget(c("toe", "tic"), hash)
## $toe
## [1] 333
## 
## $tic
## [1] 1
# show all keys
ls(hash)
## [1] "tac" "tic" "toe"
# show all keys with values
get_hash(ls(hash), hash)
## tac tic toe 
##  22   1 333
# remove key-value pairs
rm(list = c("toe", "tic"), envir = hash)
get_hash(ls(hash), hash)
## tac 
##  22
# check if keys are in hash
exists_hash(c("tac", "nothere"), hash)
##     tac nothere 
##    TRUE   FALSE
# for single keys this is also possible:
# show value for single key
hash[["tac"]]
## [1] 22
# create new key-value pair
hash[["test"]] <- 1234
get_hash(ls(hash), hash)
##  tac test 
##   22 1234
# update single value
hash[["test"]] <- 54321
get_hash(ls(hash), hash)
##   tac  test 
##    22 54321

Edit:この答えに基づいて、もう少し文脈のあるブログ記事を書きました: http://blog.ephorie.de/ hash-me-if-you-can

13
vonjd

パッケージhashが利用可能になりました: https://cran.r-project.org/web/packages/hash/hash.pdf

h <- hash( keys=letters, values=1:26 )
h <- hash( letters, 1:26 )
h$a
# [1] 1
h$foo <- "bar"
h[ "foo" ]
# <hash> containing 1 key-value pair(s).
#   foo : bar
h[[ "foo" ]]
# [1] "bar"
7
Ngọc Linh Vũ

CRANのhashpackage をご覧ください。

ダークの答えの短いバリエーション:

# Create a Color Palette Dictionary 
> color <- c('navy.blue', 'gold', 'dark.gray')
> hex <- c('#336A91', '#F3C117', '#7F7F7F')

> # Create List
> color_palette <- as.list(hex)
> # Name List Items
> names(color_palette) <- color
> 
> color_palette
$navy.blue
[1] "#336A91"

$gold
[1] "#F3C117"

$dark.gray
[1] "#7F7F7F"
5
Nettle

辞書を「偽造」しようとすると、tableから多くのマイレージを得ることができるとコメントします。

> x <- c("a","a","b","b","b","c")
> (t <- table(x))
x
a b c 
2 3 1 
> names(t)
[1] "a" "b" "c"
> o <- order(as.numeric(t))
> names(t[o])
[1] "c" "a" "b"

等.

4
Gabriel Perdue