02 vectors
105640.rar
(788 Bytes)
本附件包括:
> ##################02 Vectors####################
> ###Logical Vectors
> b=c(T,T,F,F)
> b[1:3]
[1] TRUE TRUE FALSE
> b[1]=F
> b
[1] FALSE TRUE FALSE FALSE
> ###Generating Logical Values
> 3<4
[1] TRUE
> 3>4
[1] FALSE
> c(1,2,3,4)<3
[1] TRUE TRUE FALSE FALSE
> ###Logical Conjuctions
> x=c(1,2,3,4)
> x<2|x>3
[1] TRUE FALSE FALSE TRUE
> all(x>0)
[1] TRUE
> any(x>2)
[1] TRUE
> ###Logical Subsetting
> x=c(1,2,3,4)
> x[x>2]
[1] 3 4
> ###Problem
> x=1:10
> x
[1] 1 2 3 4 5 6 7 8 9 10
> x[x%%2==0]
[1] 2 4 6 8 10
> x[x%%2==1]
[1] 1 3 5 7 9
> x[c(F,T)]
[1] 2 4 6 8 10
> x[c(T,F)]
[1] 1 3 5 7 9
> ###Character Vectors
> s=c("first", "second", "third")
> s[1:2]
[1] "first" "second"
> s[1] = "initial"
> s
[1] "initial" "second" "third"
> ###String Manipulation
> s
[1] "initial" "second" "third"
> nchar(s)
[1] 7 6 5
> substring(s,1,2:3)
[1] "in" "sec" "th"
> ###Pasting Strings Together
> paste("First", "Second", "Third")
[1] "First Second Third"
> paste("First", "Second", "Third", sep=":")
[1] "First:Second:Third"
> paste("First", "Second", "Third", sep="")
[1] "FirstSecondThird"
> ###Pasting Vectors
> paste(s,"element",sep="-")
[1] "initial-element" "second-element" "third-element"
> paste(s,collapse="->")
[1] "initial->second->third"
> ###Complex-Valued Vectors
> z=10+20i
> z
[1] 10+20i
> z=-1+0i
> sqrt(z)
[1] 0+1i
> ###Vector Mode and Length
> mode(1:10)
[1] "numeric"
> length(1:10)
[1] 10
> logical(5)
[1] FALSE FALSE FALSE FALSE FALSE
> numeric(5)
[1] 0 0 0 0 0
> ###Creating Vectors
> vector("numeric",5)
[1] 0 0 0 0 0
> vector("logical",5)
[1] FALSE FALSE FALSE FALSE FALSE
> numeric(0)
numeric(0)
> ###Type Coercion
> c(T,17)
[1] 1 17
> c(T,17,"twelve")
[1] "TRUE" "17" "twelve"
> ###Type Coercion Idioms
> x=1:10
> sum(x>5)
[1] 5
> cumsum(x>5)
[1] 0 0 0 0 0 1 2 3 4 5
> ###Explicit coercion
> "1"+"2"
Error in "1" + "2" : non-numeric argument to binary operator
> as.numeric("1")
[1] 1
> ###Named Vectors
> v=1:4
> names(v)=c("A","B","C","D")
> v
A B C D
1 2 3 4
> names(v)
[1] "A" "B" "C" "D"
> ###Subsetting Using Names
> v=1:4
> names(v)=c("A","B","C","D")
> v["A"]
A
1
> v[c("A","D")]
A D
1 4
> ###List
> lst=list(10,"eleven",T)
> ###Printing Lists
> lst
[[1]]
[1] 10
[[2]]
[1] "eleven"
[[3]]
[1] TRUE
> ###Named Lists
> list(a=10,b="eleven",T)
$a
[1] 10
$b
[1] "eleven"
[[3]]
[1] TRUE
> ###Elements and Subsets of Lists
> lst=list(10,"eleven",T)
> lst[[1]]
[1] 10
> lst[1]
[[1]]
[1] 10
> ###Extracting Named Elements
> lst=list(a=10,b="eleven",T)
> lst[["a"]]
[1] 10
> lst$a
[1] 10
> ###The NULL Object
> length(NULL)
[1] 0
> as.numeric(NULL)
numeric(0)
> as.list(NULL)
list()
[此贴子已经被作者于2007-4-5 11:10:06编辑过]