[英]Include columns from a Data frame to another in R
This is my matrix. 这是我的矩阵。 I want to include columns from other matrix in this matrix bellow:
我想在下面的矩阵中包含来自其他矩阵的列:
first.matrix<-structure(list(Datas = structure(c(18131, 18130, 18129, 18128,
18127), class = "Date"), `A~B` = c(-1.92963017062521, -3.59752795018039,
-3.72377538845192, -2.33607407809712, -2.98577937429645), `2x` = c(2.96383224677759,
2.96383224677759, 2.96383224677759, 2.96383224677759, 2.96383224677759
), `-2x` = c(-2.96383224677759, -2.96383224677759, -2.96383224677759,
-2.96383224677759, -2.96383224677759), Take = c("Acima/Entre SD",
"Acima/Entre SD", "Entrada", "Acima/Entre SD", "Acima/Entre SD"
)), row.names = c("1", "2", "3", "4", "5"), class = "data.frame")
The other matrix is this one: 另一个矩阵就是这个:
second.matrix<-structure(list(A = c(34, 33.4, 35.18, 35.4, 34.9), B = c(47.87,
48.94, 50.85, 49.68, 49.83), C = c(49.68, 49.98, 49.99, 48.79,
47.74), D = c(49.65, 46.1, 44.9, 44.92, 44.75)), class = "data.frame", row.names = c(NA,
5L))
This is what I need: As you can see the first matrix
has a column like this A~B
. 这就是我需要的:正如你所看到的,
first matrix
有一个像A~B
这样的列。 So, the code should go to the second.matrix
Identifies the column before and after the ~
, extract it and include in the first matrix. 因此,代码应该转到
second.matrix
标识~
之前和之后的列,将其提取并包含在第一个矩阵中。
Any help guys? 有帮助吗?
PS: In my real code the first.matrix matrix are in a list of matrix. PS:在我的实际代码中,first.matrix矩阵在矩阵列表中。 But if you help me with this code I believe I will be able to extend to my real code.
但是,如果你帮助我使用这段代码,我相信我将能够扩展到我的真实代码。
Many thanks guys 非常感谢你们
If first.matrix
always includes ~
for indicating the merging of the columns, 如果
first.matrix
总是包含~
用于指示列的合并,
# To find the index of the columns including ~ inside,
index <- strsplit(names(first.matrix)[grepl("~",names(first.matrix))],"~")
# cbind wrt the index
lapply(seq(index),function(i) cbind(first.matrix,second.matrix[,index[[i]]]))
gives, 给,
[[1]]
Datas A~B 2x -2x Take A B
1 2019-08-23 -1.929630 2.963832 -2.963832 Acima/Entre SD 34.00 47.87
2 2019-08-22 -3.597528 2.963832 -2.963832 Acima/Entre SD 33.40 48.94
3 2019-08-21 -3.723775 2.963832 -2.963832 Entrada 35.18 50.85
4 2019-08-20 -2.336074 2.963832 -2.963832 Acima/Entre SD 35.40 49.68
5 2019-08-19 -2.985779 2.963832 -2.963832 Acima/Entre SD 34.90 49.83
If you want to keep the colnames'
A and
B` 如果你想保留
colnames'
A and
B`
New_df <- cbind(first.matrix, A = second.matrix$A, B = second.matrix$B)
# Datas A~B 2x -2x Take A B
# 1 2019-08-23 -1.929630 2.963832 -2.963832 Acima/Entre SD 34.00 47.87
# 2 2019-08-22 -3.597528 2.963832 -2.963832 Acima/Entre SD 33.40 48.94
# 3 2019-08-21 -3.723775 2.963832 -2.963832 Entrada 35.18 50.85
# 4 2019-08-20 -2.336074 2.963832 -2.963832 Acima/Entre SD 35.40 49.68
# 5 2019-08-19 -2.985779 2.963832 -2.963832 Acima/Entre SD 34.90 49.83
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.