R中的数据重塑用法图解

转置矩阵

R使我们能够通过提供t()函数来计算矩阵或数据帧的转置。此t()函数将矩阵或数据帧作为输入, 并返回输入矩阵或数据帧的转置。 t()函数的语法如下：

``t(Matrix/data frame)``

``````a <- matrix(c(4:12), nrow=3, byrow=TRUE)
a
print("Matrix after transpose\n")
b <- t(a)
b``````

在数据框中连接行和列

R允许我们连接多个向量以创建数据帧。为此, R提供了cbind()函数。 R还提供了rbind()函数, 该函数允许我们合并两个数据帧。在某些情况下, 我们需要合并数据帧以访问依赖于这两个数据帧的信息。 cbind()函数和rbind()函数具有以下语法。

``````cbind(vector1, vector2, .......vectorN)
rbind(dataframe1, dataframe2, ........dataframeN)``````

``````#Creating vector objects
Name <- c("Shubham Rastogi", "Nishka Jain", "Gunjan Garg", "Sumit Chaudhary")
Marks <- c(255, 355, 455, 655)

#Combining vectors into one data frame

#Printing data frame
print(info)

# Creating another data frame with similar columns
new.stuinfo <- data.frame(
)

cat("# # # The Second data frame\n")

#Printing the data frame.
print(new.stuinfo)

# Combining rows form both the data frames.
all.info <- rbind(info, new.stuinfo)

cat("# # # The combined data frame\n")

# Printing the result.
print(all.info)``````

合并数据框

R提供merge()函数来合并两个数据帧。在合并过程中, 存在一个约束, 即；数据框必须具有相同的列名。

``````library(MASS)
merging_pima<- merge(x = Pima.te, y = Pima.tr, by.x = c("bp", "bmi"), by.y = c("bp", "bmi")
)
print(merging_pima)
nrow(merging_pima)``````

熔铸

``````library(MASS)
print(ships)``````

融化数据

``````library(MASS)
library(reshape2)
molten_ships <- melt(ships, id = c("type", "year"))
print(molten_ships)``````

熔解数据的铸造

``````library(MASS)
library(reshape2)
#Melting the data
molten.ships <- melt(ships, id = c("type", "year"))
print("Molted Data")
print(molten.ships)
#Casting of data
recasted.ship <- dcast(molten.ships, type+year~variable, sum)
print("Cast Data")
print(recasted.ship)``````