[英]Compare dataframes and vectors in R
I have a huge data frame in R and I want to compare the first four columns with a vector.我在 R 中有一个巨大的数据框,我想将前四列与一个向量进行比较。 This is my data frame:这是我的数据框:
> head(MyTable)
config.1. config.2. config.3. config.4. kernel orden.1. orden.2. orden.3. orden.4.
1 gen(1) 2*gen(2)+2*gen(1) 3*gen(2)+2*gen(1) 2*gen(2)+gen(1) gen(4)-2*gen(3)+2*gen(2)-gen(1) 1 2 3 4
2 gen(1) 4*gen(2)+2*gen(1) 3*gen(2)+2*gen(1) 2*gen(2)+gen(1) gen(4)+2*gen(3)-2*gen(2)-gen(1) 1 3 2 4
3 gen(1) 6*gen(2)+2*gen(1) 3*gen(2)+2*gen(1) 2*gen(2)+gen(1) 3*gen(4)+2*gen(3)-2*gen(2)-3*gen(1) 3 1 4 2
4 gen(1) 7*gen(2)+2*gen(1) 3*gen(2)+2*gen(1) 2*gen(2)+gen(1) 2*gen(4)+gen(3)-gen(2)-2*gen(1) 3 1 4 2
5 gen(1) 8*gen(2)+2*gen(1) 3*gen(2)+2*gen(1) 2*gen(2)+gen(1) 5*gen(4)+2*gen(3)-2*gen(2)-5*gen(1) 3 1 4 2
6 gen(1) 9*gen(2)+2*gen(1) 3*gen(2)+2*gen(1) 2*gen(2)+gen(1) 3*gen(4)+gen(3)-gen(2)-3*gen(1) 3 1 4 2
Where the first columns are strings.第一列是字符串。 I want to compare the first four columns in every row with the vector:我想将每一行的前四列与向量进行比较:
> MyConfig
[1] "gen(1)" "gen(2)" "3*gen(2)+2*gen(1)" "2*gen(2)+gen(1)"
Every row of the data frame has three columns equal to the columns in the vector and one different.数据框的每一行都有三列,等于向量中的列,一列不同。 I need a new data frame with TRUE or FALSE values.我需要一个具有 TRUE 或 FALSE 值的新数据框。
I tried to compare the submatrix MyTable[,1:4] with the vector MyConfig using == and I get:我尝试使用 == 将子矩阵 MyTable[,1:4] 与向量 MyConfig 进行比较,我得到:
> head(MyTable[,1:4]==MyConfig)
config.1. config.2. config.3. config.4.
[1,] TRUE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE FALSE
[3,] FALSE FALSE TRUE FALSE
[4,] FALSE FALSE FALSE TRUE
[5,] TRUE FALSE FALSE FALSE
[6,] FALSE FALSE FALSE FALSE
But if I compare the cells manually this is the result:但如果我手动比较单元格,结果如下:
> MyTable[1,3]==MyConfig[3]
[1] TRUE
So, cell by cell I get the result I´m expecting.所以,逐个细胞我得到了我期待的结果。 But if I compare the complete table, the result is different.但是如果我比较完整的表格,结果就不同了。
The output I´m expecting is:我期待的 output 是:
> head(MyTable[,1:4]==MyConfig)
config.1. config.2. config.3. config.4.
[1,] TRUE FALSE TRUE TRUE
[2,] TRUE FALSE TRUE TRUE
[3,] TRUE FALSE TRUE TRUE
[4,] TRUE FALSE TRUE TRUE
[5,] TRUE FALSE TRUE TRUE
[6,] TRUE FALSE TRUE TRUE
We may need either rep
licate the 'MyConfig' values我们可能需要复制“ rep
”值
MyTable[,1:4]==MyConfig[col(MyTable[, 1:4])]
Or t
ranspose the dataset, do the comparison and t
ranspose again或者t
置数据集,进行比较并t
转置
t(t(MyTable[1:4] == MyConfig)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.