列表和数据框
1.列表
list函数创建列表
> (a_list <- list(c(1,1,2,5,14,42),month.abb,matrix(c(3,-8,1,-3),nrow=2),asin))
[[1]]
[1] 1 1 2 5 14 42
[[2]]
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
[[3]]
[,1] [,2]
[1,] 3 1
[2,] -8 -3
[[4]]
function (x) .Primitive("asin")
给列表元素命名
> names(a_list) <- c("catalan","month","involutary","arcsin")
> a_list
$catalan
[1] 1 1 2 5 14 42
$month
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
$involutary
[,1] [,2]
[1,] 3 1
[2,] -8 -3
$arcsin
function (x) .Primitive("asin")
列表长度是它顶层元素的数目:
> length(a_list)
[1] 4
列表没有维数
> dim(a_list)
NULL
使用as.list函数将向量转换成列表
> a_vector <- c(1,6,7,8)
> as.list(a_vector)
[[1]]
[1] 1
[[2]]
[1] 6
[[3]]
[1] 7
[[4]]
[1] 8
2.数据框
data.frame函数创建数据框
> (a_data_frame <- data.frame(x=letters[1:5],y=rnorm(5),z=runif(5)>0.5))
x y z
1 a 0.47620421 TRUE
2 b -0.04279112 FALSE
3 c 1.49076637 FALSE
4 d -0.41444402 TRUE
5 e -1.03173668 TRUE
每一列中的元素类型一样
基本数据框操作
t函数转置
> t(a_data_frame)[,1] [,2] [,3] [,4] [,5]
x "a" "b" "c" "d" "e"
y " 0.47620421" "-0.04279112" " 1.49076637" "-0.41444402" "-1.03173668"
z " TRUE" "FALSE" "FALSE" " TRUE" " TRUE"
cbind, rbind连接数据框
> (a_data_frame <- data.frame(x=letters[1:5],y=rnorm(5),z=runif(5)>0.5))x y z
1 a -0.17804129 FALSE
2 b -1.28864149 FALSE
3 c -0.99590504 FALSE
4 d 0.01776164 FALSE
5 e 1.37784685 FALSE
> (another_data_frame <- data.frame(z=rlnorm(5),y=sample(5),x=letters[3:7]))
z y x
1 2.6574401 4 c
2 3.3455939 3 d
3 0.4205031 1 e
4 3.3006536 5 f
5 1.7008018 2 g
> rbind(a_data_frame,another_data_frame)
x y z
1 a -0.17804129 0.0000000
2 b -1.28864149 0.0000000
3 c -0.99590504 0.0000000
4 d 0.01776164 0.0000000
5 e 1.37784685 0.0000000
6 c 4.00000000 2.6574401
7 d 3.00000000 3.3455939
8 e 1.00000000 0.4205031
9 f 5.00000000 3.3006536
10 g 2.00000000 1.7008018
> cbind(a_data_frame,another_data_frame)
x y z z y x
1 a -0.17804129 FALSE 2.6574401 4 c
2 b -1.28864149 FALSE 3.3455939 3 d
3 c -0.99590504 FALSE 0.4205031 1 e
4 d 0.01776164 FALSE 3.3006536 5 f
5 e 1.37784685 FALSE 1.7008018 2 g
R语言学习(3)