- 分析中的資料形態
- R 語言的資料型態
- 活用R 語言的資料型態
Wush Wu
國立台灣大學
資料衡量尺度 | 變數形態 | 特性 | |
---|---|---|---|
1 | 名目資料(nomial) | 質化 | 類別 |
2 | 順序資料(ordinal) | 質化 | 優先順序 |
3 | 區間資料(interval) | 量化 | 大小距離 |
4 | 比例資料(ratio) | 量化 | 比值 |
140.118.1.1
#R,Text Mining Series,Taiwan R User Group
"
或'
來包覆要輸入的文字
\"
來輸入"
或\'
plot(cars, main="\"hello world\"")
paste
x <- "abc";y <- "bbb"
paste(x, y, sep=",")
## [1] "abc,bbb"
strsplit
strsplit(x, "b")
## [[1]]
## [1] "a" "c"
nchar
nchar(x)
## [1] 3
substring
substring(x, 1, 2)
## [1] "ab"
T
、TRUE
、F
或FALSE
輸入x <- 1
x < 2
## [1] TRUE
x <= 1
## [1] TRUE
if (T) {
print("This is TRUE")
} else {
print ("This is FALSE")
}
## [1] "This is TRUE"
!TRUE
## [1] FALSE
T & T
## [1] TRUE
T | F
## [1] TRUE
+
1 + 2
## [1] 3
-
1 - 2
## [1] -1
*
1 * 2
## [1] 2
/
1L / 2L
## [1] 0.5
length(0L)
## [1] 1
:
或c()
快速建立Vector1:3
## [1] 1 2 3
c(1L,2L,3L)
## [1] 1 2 3
1:3 + 2:4
## [1] 3 5 7
1:2 + 1:3
## Warning in 1:2 + 1:3: 較長的物件長度並非較短物件長度的倍數
## [1] 2 4 4
1:2 + 1:3
## Warning in 1:2 + 1:3: 較長的物件長度並非較短物件長度的倍數
## [1] 2 4 4
1 2 1 2
1 2 3
2 4 4
f1 <- function() 1:1000 + 1
f2 <- function() {
r <- integer(1000)
for(i in 1:1000) r[i] <- i + 1
r
}
expr | median(nano seconds) | |
---|---|---|
1 | f1() | 3434.50 |
2 | f2() | 660192.00 |
x <- c(1L, 2.0, "3")
class(x)
## [1] "character"
x
## [1] "1" "2" "3"
x <- matrix(1:4, 2, 2)
class(x)
## [1] "matrix"
x[2]
## [1] 2
x[2] <- as.character(x[2])
x
## [,1] [,2]
## [1,] "1" "3"
## [2,] "2" "4"
1:2
## [1] 1 2
paste(1:2)
## [1] "1" "2"
c(TRUE, FALSE)
## [1] TRUE FALSE
summary
?summary
summary(1:10)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.00 3.25 5.50 5.50 7.75 10.00
summary(paste(1:10))
## Length Class Mode
## 10 character character
class
typeof
mode
class(1)
## [1] "numeric"
class(1L)
## [1] "integer"
typeof(1)
## [1] "double"
typeof(1L)
## [1] "integer"
mode(1)
## [1] "numeric"
mode(1L)
## [1] "numeric"
numeric
、logical
或character
S3
方法Date
v.s. Integer
[
x <- 11:20
x
## [1] 11 12 13 14 15 16 17 18 19 20
[
+ logicalx < 13
## [1] TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[x < 13]
## [1] 11 12
[
+ integer/numericx[1:2]
## [1] 11 12
head(x, 2)
## [1] 11 12
[
names(x) <- letters[1:10]
x
## a b c d e f g h i j
## 11 12 13 14 15 16 17 18 19 20
x["d"]
## d
## 14
x[c("a", "b")]
## a b
## 11 12
height <- c("John" = 198, "Tom" = 166, "Peter" = 170)
height
## John Tom Peter
## 198 166 170
height
是有名字的向量還是沒有名字的向量?height
是numeric
、integer
還是character
?[
回答以下問題:
height
中取出"Peter"的資料?sort
[
來作答最方便?height2 <- c("Tom" = 170, "Peter" = 185, "John" = 200)