R: 基础学习

2023-12-31 14:37:41

1. Arithmetic with R

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Exponentiation: ^
  • Modulo: %% (模数:指的是a/n的余数)

2. 数据类型

2.1 Vector

-- one dimensional array. The elements in a vector all have the same data type.

2.2 Matrix

-- two dimensional array. The elements in a matrix all have the same data type.

?1) Construct?a?matrix (with?3?rows?that?contain?the?numbers?1?up?to?9)

matrix(1:9, byrow = TRUE, nrow = 3)

2) Add a name for row and column

rownames, colnames

rownames(my_matrix) <- row_names_vector
colnames(my_matrix) <- col_names_vector

3) Calculate the total of row (create a new vector)

rowSums, colSums

rowSums(my_matrix)

4) Add a column / row

cbind, rbind

big_matrix <- cbind(matrix1, matrix2, vector1 ...)

5) Selection of matrix elements

my_matrix[ , n], my_matirx[n, ]

2.3 Factor

-- two dimensional objects. Within a column all elements have the same data tyoe, but different columns can be of different data type.

encode the vector as a factor

factor( )

create an ordered factor

factor(some_vector,
       ordered = TRUE,
       levels = c("lev1", "lev2" ...))

设置 factors' level

levels(factor_vector) <- c("name1", "name2",...)

总结:?summary()

2.4 data frame

1) have a look at the head/tail:?head(), tail()?

2) look the structure:?str()?

3) construct a data frame:?data.frame()

4) selection of data frame elements

df[n, m]?# 和定坐标差不多

df[1:5, m] #选择第m列的1到5行

subset(my_df, some_condition)

5) sort the data frame

2.5 List

1) creat a list

my_list <- list(comp1, comp2, ...)

2) create a named list

my_list <- list(name11 = your_comp1, name2 = your_comp2)
my_list <- list(your_comp1, your_comp2)
names(my_list) <- c("name1", "name2")

3) select elements from a list

we can use [[ ]] or $ sign to select

文章来源:https://blog.csdn.net/yilinstar_610/article/details/135221065
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。