# 加载中...

• 博客等级：
• 博客积分：0
• 博客访问：1,321,645
• 关注人气：828
• 获赠金笔：0支
• 赠出金笔：0支
• 荣誉徽章：

## 【T】R--筛选--[用来提取

(2014-01-27 17:24:29)

### 数据提取

http://qinqianshan.com/filter-the-data-subset-which/

[ 用来提取对象相同的类型，可以包含不止一个元素

[[用来提取额 list或data frame里面的元素，一般只能提取单个的元素

\$通过名字来提取 list或data frame的元素;

> x <- c("a", "b", "c", "c", "d", "a")
> x[1]
[1] "a"
> x[2]
[1] "b"
> x[1:4]
[1] "a" "b" "c" "c"
> x[x > "a"]
[1] "b" "c" "c" "d"
> u <- x > "a"
> u
[1] FALSE TRUE TRUE TRUE TRUE FALSE
> x[u]
[1] "b" "c" "c" "d"

x <- matrix(1:6, 2, 3)
> x[1, 2]
[1] 3
> x[2, 1]
[1] 2
Indices can also be missing.
> x[1, ]
[1] 1 3 5
> x[, 2]
[1] 3 4

> x <- matrix(1:6, 2, 3)
> x[1, 2]
[1] 3
> x[1, 2, drop = FALSE]
[,1]
[1,] 3

> x <- matrix(1:6, 2, 3)
> x[1, ]
[1] 1 3 5
> x[1, , drop = FALSE]
[,1] [,2] [,3]
[1,] 1 3 5

list的提取

> x <- list(foo = 1:4, bar = 0.6)
> x[1]
\$foo
[1] 1 2 3 4
> x[[1]]
[1] 1 2 3 4
> x\$bar
[1] 0.6
> x[["bar"]]
[1] 0.6
> x["bar"]
\$bar
[1] 0.6

> x <- list(foo = 1:4, bar = 0.6, baz = "hello")
> x[c(1, 3)]
\$foo
[1] 1 2 3 4
\$baz
[1] "hello"

\$仅仅适用于原始的名字，如果改名字了，还是得用[[]]

> x <- list(foo = 1:4, bar = 0.6, baz = "hello")
> name <- "foo"
> x[[name]] ## computed index for `foo'

[1] 1 2 3 4

> x\$name ## element `name' doesn't exist!

NULL

> x\$foo

[1] 1 2 3 4 ## element `foo' does exist

The [[ can take an integer sequence.

> x <- list(a = list(10, 12, 14), b = c(3.14, 2.81))

> x[[c(1, 3)]]

[1] 14

> x[[1]][[3]]

[1] 14

> x[[c(2, 1)]]

[1] 3.14

[[和\$可以匹配部分名字.

> x <- list(aardvark = 1:5)

> x\$a

[1] 1 2 3 4 5

> x[["a"]]

NULL

> x[["a", exact = FALSE]]

[1] 1 2 3 4 5

> x <- c(1, 2, NA, 4, NA, 5)

[1] 1 2 4 5

> x <- c(1, 2, NA, 4, NA, 5)

> y <- c("a", "b", NA, "d", NA, "f")

> good <- complete.cases(x, y)

> good

[1] TRUE TRUE FALSE TRUE FALSE TRUE

> x[good]

[1] 1 2 4 5

> y[good]

[1] "a" "b" "d" "f"

> airquality[1:6, ]

Ozone Solar.R Wind Temp Month Day

1 41 190 7.4 67 5 1

2 36 118 8.0 72 5 2

3 12 149 12.6 74 5 3

4 18 313 11.5 62 5 4

5 NA NA 14.3 56 5 5

6 28 NA 14.9 66 5 6

> good <- complete.cases(airquality)

> airquality[good, ][1:6, ]  ##非常强大的complete.cases

Ozone Solar.R Wind Temp Month Day

1 41 190 7.4 67 5 1

2 36 118 8.0 72 5 2

3 12 149 12.6 74 5 3

4 18 313 11.5 62 5 4

7 23 299 8.6 65 5 7

ps：内容来自于Roger D. Peng的《Computing for Data Analysis》

0

• 评论加载中，请稍候...

发评论

以上网友发言只代表其个人观点，不代表新浪网的观点或立场。

新浪BLOG意见反馈留言板　电话：4000520066 提示音后按1键（按当地市话标准计费）　欢迎批评指正

新浪公司 版权所有