程序小白学习R语言记录~~~

时间:2022-10-09 00:16:52

2018330日星期

笔记lecture2(如果乱码 选择file  recode   UTF-8

l R语言 lecture2

l 一、Lecture2中函数类型:1.sqrt()平方根

2. rnorm()随机数字,如rnorm100)即为随机数字100

3. Hist()函数,根据数集画出柱状图

4. Args()检查函数功能,比如argsrnorm

5. Round()x舍为指定位数的小数,round(x, digits=n

 

二、数据类型:

a四种主要类型有logicalnumericalcharacterinteger

bclass()检验数据类型,如classTRUE)输出结果为“logical

C.给数字加上L 表明其为整数,如3L class3L)输出为“integer

D.用  is.integer()检验是否为整数,如is.integer(3),输出为FALSE

E. Character要加引号,且要用半角

F.As.numeric  数据的类型转换  :把它转换为数值型(应用:转换数值 为字符)

 

三、创建向量vector

A vector is a sequence of data elements of the same data type. A vector can only hold elements of the same type. If you have a vector consisting of numbers and character, R will turn ALL of your values into character data! If you have a vector consisting of numbers and logicals, R will turn ALL of your values into numeric data!(character>numeric>logical)

 

A. 可以用c()创建向量

B. names()函数给向量命名。,将标签附加到函数。例子如下:

suits <- c("spades", "hearts", "diamonds", "clubs")

remain <- c(11, 12, 11, 13)

names(remain) <- suits

remain

此时输remain为:

spades   hearts diamonds    clubs

      11       12       11       13

 

 

四、向量的计算

向量的算法对应算数位置

长度不一样的向量,短的向量会循环自动补齐

注意区分大小写,大小写不同代表的值不一样

Mean function算术平均值

Median ---中位数

Names ---命名

 

五、# Sequences, Repetition, sorting, and Lengths #

1.输出一到十序列的方法:a. 110

                      b. seq()函数, seqfrom=1to=10)。。。。如果有间隔interval2,则为seqfrom=1to=10by2

2.Repetition重复rep(x = c(3, 6, 8), times = 3)

rep(x = c(3, 6, 8), each = 2)

rep(x = c(3, 6, 8), times = 3, each = 2)

3.Sorting排序  sort(x = c(2.5, -1, -10, 3.44), decreasing = FALSE)

              sort(x = c(2.5, -1, -10, 3.44), decreasing = TRUE)

4. length  The length function tell us how many elements exist in a vector

length(x = c(3, 2, 8, 1))length513)等

 

 

六、# Subsetting your Vectors #截取向量

1.Suppose you want to select the first element from this vector, you can use square brackets for this   remain[1]

2.选择两个元素  remain[c(4, 1)]

3. Create a vector that contains all the information that's in the `remain` vector, except for the spades count排除某个元素   

   remain[-1]

remain[-1]

    hearts diamonds    clubs

       12       11       13

4.可以根据逻辑来选择向量中的元素remain[c(FALSE, TRUE, FALSE, TRUE)]

  即选择24元素

5.也可以The above expression is the same as the bellowing one 

 remain[remain > 11]

如果直接remain > 11

结果是remain > 11

      spades   hearts diamonds    clubs

       FALSE     TRUE    FALSE     TRUE