R言語 リスト - R Lists

リストの作成

MyList <- list(1:5, c("dog", "cat", "bee"), c(TRUE, FALSE))
MyList
## [[1]]
## [1] 1 2 3 4 5
## 
## [[2]]
## [1] "dog" "cat" "bee"
## 
## [[3]]
## [1]  TRUE FALSE
str(MyList)
## List of 3
##  $ : int [1:5] 1 2 3 4 5
##  $ : chr [1:3] "dog" "cat" "bee"
##  $ : logi [1:2] TRUE FALSE
a <- 1:3
b <- c("dog", "cat", NA)
c <- c(TRUE, TRUE, FALSE)
d <- data.frame(a, b, c)
MyList2 <- list(a, b, c, d)
MyList2
## [[1]]
## [1] 1 2 3
## 
## [[2]]
## [1] "dog" "cat" NA   
## 
## [[3]]
## [1]  TRUE  TRUE FALSE
## 
## [[4]]
##   a    b     c
## 1 1  dog  TRUE
## 2 2  cat  TRUE
## 3 3 <NA> FALSE
str(MyList2)
## List of 4
##  $ : int [1:3] 1 2 3
##  $ : chr [1:3] "dog" "cat" NA
##  $ : logi [1:3] TRUE TRUE FALSE
##  $ :'data.frame':    3 obs. of  3 variables:
##   ..$ a: int [1:3] 1 2 3
##   ..$ b: Factor w/ 2 levels "cat","dog": 2 1 NA
##   ..$ c: logi [1:3] TRUE TRUE FALSE

リストの名前

names(MyList2)
## NULL
MyList2 <- list(first = a, second = b, third = c, forth = d)
names(MyList2) <- c("first", "second", "third", "forth")
str(MyList2)
## List of 4
##  $ first : int [1:3] 1 2 3
##  $ second: chr [1:3] "dog" "cat" NA
##  $ third : logi [1:3] TRUE TRUE FALSE
##  $ forth :'data.frame':  3 obs. of  3 variables:
##   ..$ a: int [1:3] 1 2 3
##   ..$ b: Factor w/ 2 levels "cat","dog": 2 1 NA
##   ..$ c: logi [1:3] TRUE TRUE FALSE
MyList2
## $first
## [1] 1 2 3
## 
## $second
## [1] "dog" "cat" NA   
## 
## $third
## [1]  TRUE  TRUE FALSE
## 
## $forth
##   a    b     c
## 1 1  dog  TRUE
## 2 2  cat  TRUE
## 3 3 <NA> FALSE

 リストの成分へアクセス

MyList2$first
## [1] 1 2 3
MyList2$second
## [1] "dog" "cat" NA
MyList2[[1]]
## [1] 1 2 3
MyList2[[2]]
## [1] "dog" "cat" NA
MyList2[["first"]]
## [1] 1 2 3
MyList2[["second"]]
## [1] "dog" "cat" NA
MyList2$first[2]
## [1] 2
MyList2[[2]][2:3]
## [1] "cat" NA
MyList2[["second"]][c(1, 2)]
## [1] "dog" "cat"
MyList2$first[2] <- 99

リストに新しい成分を加える

MyList2[[5]] <- 1:10

リストの成分削除

MyList2[[5]] <- NULL