- str()
在很多語言里可以將其他類型轉化為字符串,不過在R中會返回數據類型。
data(iris)
str(iris)
返回:
'data.frame': 100 obs. of 5 variables:
$ Sepal.Length: num 7 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2 ...
$ Sepal.Width : num 3.2 3.2 3.1 2.3 2.8 2.8 3.3 2.4 2.9 2.7 ...
$ Petal.Length: num 4.7 4.5 4.9 4 4.6 4.5 4.7 3.3 4.6 3.9 ...
$ Petal.Width : num 1.4 1.5 1.5 1.3 1.5 1.3 1.6 1 1.3 1.4 ...
$ Species : Factor w/ 2 levels "versicolor","virginica": 1 1 1 1 1 1 1 1 1 1 ...
- 通過鏈接讀取數據
site <- "http://random.org/integers/" # 這是一個生成隨機數的網站
# 產生兩列10行隨機數,最小值100,最大值200
query <- "num=10&min=100&max=200&col=2&base=10&format=plain&rnd=new"
txt <- paste(site, query, sep="?") # 網址
nums <- read.table(file=txt) # 讀取
- 反引號
df <- data.frame(x=rnorm(5),y=runif(5))
names(df) <- 1:2
取第一列,如果是這樣則會報錯:
df$1
報一個“錯誤: unexpected numeric constant in "df$1"”的錯誤。
但是這樣可以:
df$`1`
df$后tab鍵提示出來也是會有反引號的。
做線性回歸也可以:
lm(`2`~`1`,data=df)
- 對數據框的操作
新建數據:
sales <- expand.grid(country = c('USA', 'UK', 'FR'),
product = c(1, 2, 3))
sales$revenue <- rnorm(dim(sales)[1], mean=100, sd=10)
transform增加列:
usd2eur <- 1.5
transform(sales, euro = revenue * usd2eur)
- cut / table
cut可以把數據分成想要的區(qū)間:
irisSL <- iris$Sepal.Length
# 分成五個bins
cut(irisSL, 5)
# 也可以按我們想要的范圍分割
cut(irisSL, breaks = seq(1,8,1))
可以用table統(tǒng)計每個范圍的數目:
table(cut(irisSL, 5))
返回:
(4.9,5.5] (5.5,6.1] (6.1,6.7] (6.7,7.3] (7.3,7.9]
12 33 35 13 7
歡迎關注~