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\n")
# Print the data frame.
print(addresses)
# Create another data frame with similar columns
new.address <- data.frame(
city = c("Lowry","Charlotte"),
state = c("CO","FL"),
zipcode = c("80230","33949"),
stringsAsFactors=FALSE
)
# Print a header.
cat("# # # The Second data frame\n")
# 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\n")
# Print the result.
print(all.addresses)
当我们上面的代码执行时,它产生以下结果:
# # # # The First data frame
city state zipcode
[1,] "Tampa" "FL" "33602"
[2,] "Seattle" "WA" "98104"
[3,] "Hartford" "CT" "6161"
[4,] "Denver" "CO" "80294"
# # # The Second data frame
city state zipcode
1 Lowry CO 80230
2 Charlotte FL 33949
# # # The combined data frame
city state zipcode
1 Tampa FL 33602
2 Seattle WA 98104
3 Hartford CT 6161
4 Denver CO 80294
5 Lowry CO 80230
6 Charlotte FL 33949
合并数据帧
我们可以通过使用 merge()函数合并两个数据帧。该数据帧必须在其上合并发生相同的列名。
在下面的例子中,我们考虑对皮马印第安人妇女的糖尿病在可用的数据集库名称 "MASS". 我们合并基础血压(“BP”)和身体质量指数(“BMI”)的值,两个数据集。上用于合并选择这两列,其中,这两个变量的值匹配在两个数据集组合在一起的记录,以形成一个单一的数据帧。
library(MASS)
merged.Pima <- merge(x=Pima.te, y=Pima.tr,
by.x=c("bp", "bmi"),
by.y=c("bp", "bmi")
)
print(merged.Pima)
nrow(merged.Pima)
当我们上面的代码执行时,它产生以下结果:
bp bmi npreg.x glu.x skin.x ped.x age.x type.x npreg.y glu.y skin.y ped.y
1 60 33.8 1 117 23 0.466 27 No 2 125 20 0.088
2 64 29.7 2 75 24 0.370 33 No 2 100 23 0.368
3 64 31.2 5 189 33 0.583 29 Yes 3 158 13 0.295
4 64 33.2 4 117 27 0.230 24 No 1 96 27 0.289
5 66 38.1 3 115 39 0.150 28 No 1 114 36 0.289
6 68 38.5 2 100 25 0.324 26 No 7 129 49 0.439
7 70 27.4 1 116 28 0.204 21 No 0 124 20 0.254
8 70 33.1 4 91 32 0.446 22