Beginner R-data frame and R representation: the use of data.frame(), rbind(), cbind(), head(), tail(), apply() and other functions

One, the composition of the data frame

The data frame is a matrix of data, but the columns in the data frame can be different types of data.

Each column of the data frame is a variable, and each row is an observation.

1. Use the data.frame() function to build a data frame in R

(1) Construct a data frame from x1 and x2

x1=c(171,175,159,155,152,160)
x2=c(57,64,41,38,35,40)

X = data.frame(x1,x2)
print(X)

Insert picture description here

(2) Name the column of the data frame

Y = data.frame('身高' = x1,'体重' = x2)
print(Y)

Insert picture description here

Second, the composition of the data frame

1. Use rbind() in R to merge two or more vectors, matrices or data frames by row to form a new data frame

print(rbind(x1,x2))

Insert picture description here

2. Use cbind() in R to combine two or more vectors, matrices or data frames by column to form a new data frame

print(cbind(x1,x2))

Insert picture description here

3. Use the head() and tail() functions in R to display by line

① Use the head() function in R to display the first few rows of data (six rows by default)

head(X)

Insert picture description here

② Use tail() function in R to display the last few rows of data (six rows by default)

tail(X,3)

Insert picture description here

Three, the application of the data frame

For data frames, the application function **apply()** is usually used to perform statistical calculations on rows and columns:
apply(X,MARGIN,FUN)

Among them:
X is the data frame or matrix
MARGIN is used to specify whether to perform operations on rows or columns, MARGIN=1 means for rows, MARGIN=2 means for columns
FUN is used to specify calculation functions

1. Summation

X_R = apply(X,1,sum)
print(X_S)

Insert picture description here

2. Sum by column

X_C = apply(X,2,sum)
print(X_C)

Insert picture description here

cbind(X,'行的和'= X_R)

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45154565/article/details/109242120