R语言中的数据重塑是关于变化的数据分为行和列的方式。大多数R地数据处理的时候是通过将输入的数据作为一个数据帧进行。这是很容易提取一个数据帧的行和列数据,但在某些情况,当我们需要的数据帧的格式是不同的来自收到它的格式。 R有许多函数用来分割,合并,改变行列,反之亦然在一个数据帧。
接合列和行中的数据帧
我们可以加入多个向量创建使用 cbind()函数返回数据帧。同时,我们也可以使用 rbind()函数合并两个数据帧。
# Create vector objects.
city <-
c("Tampa","Seattle","Hartford","Denver")
state <- c("FL","WA","CT","CO")
zipcode <- c(33602,98104,06161,80294)
# Combine above three vectors into one data frame.
addresses <- cbind(city,state,zipcode)
# Print a header.
cat("# # # # The First data frame
")
# Print the data frame.
print(addresses)
# Create another data frame with similar columns
new.address <- data.frame(
)
# Print a header.
cat("# # # The Second data frame
")
# Print the data frame.
print(new.address)
# Combine rows form both the data frames.
all.addresses <- rbind(addresses,new.address)
# Print a header.
cat("# # # The combined data frame
")
# Print the result.
print(all.addresses)
当我们上面的代码执行时,它产生以下结果:
# # # # The First data frame
[1,] "Tampa"
[2,] "Seattle"
[3,] "Hartford" "CT"
[4,] "Denver"
# # # The Second data frame
1
2 Charlotte
# # # The combined data frame
1
2
3
4
5
6 Charlotte
合并数据帧
我们可以通过使用 merge()函数合并两个数据帧。该数据帧必须在其上合并发生相同的列名。
在下面的例子中,我们考虑对皮马印第安人妇女的糖尿病在可用的数据集库名称 "MASS". 我们合并基础血压(“BP”)和身体质量指数(“BMI”)的值,两个数据集。上用于合并选择这两列,其中,这两个变量的值匹配在两个数据集组合在一起的记录,以形成一个单一的数据帧。
library(MASS)
merged.Pima <- merge(x=Pima.te, y=Pima.tr,
)
print(merged.Pima)
nrow(merged.Pima)
当我们上面的代码执行时,它产生以下结果:
1
2
3
4
5
6
7
8