简体   繁体   English

比较 R 中的两个数据帧

[英]Compare two dataframes in R

I have two dataframes in R and want to compare any entries of rows.我在 R 中有两个数据框,想比较行的任何条目。 I want two check if the value of the first entrie, second entrie etc. of first (any) row of the first dataframe is bigger as the entrie of the first entrie of the the first row of the second dataframe.我想要两次检查第一个数据帧的第一(任何)行的第一个条目、第二个条目等的值是否大于第二个数据帧的第一行的第一个条目的条目。 Afterwards it should give me a TRUE if all entries are bigger and in the intervall (0,2).之后,如果所有条目都更大并且在间隔 (0,2) 中,它应该给我一个 TRUE。 It looks like this.它看起来像这样。

Dataframe 1

Letter 2011 2012 2013
A       2     3    5
B       6     6    6
C       5     4    8

Dataframe 2

Letter 2011  2012 2013
A        1     1    4
C        5     5    5


Result for example like this (comparing rows A and A and C and C)

Letter  2011   2012  2013
 A        1      2     1      TRUE- all ok
 C        0      -1    3      FALSE- second entrie smaller of the first table and third entrie much more 
                              bigger of the first table.

One approach could be to convert data to long format, perform an inner_join subtract values, check if all the values are in range and get the data back in wide format.一种方法可能是将数据转换为长格式,执行inner_join减去值,检查所有值是否在范围内并以宽格式返回数据。

library(dplyr)
library(tidyr)

df1 %>% pivot_longer(cols = -Letter) %>%
   inner_join(df2 %>% pivot_longer(cols = -Letter), by = c("Letter", "name")) %>%
   mutate(value = value.x - value.y) %>%
   group_by(Letter) %>%
   mutate(check = all(between(value, 0, 2))) %>%
   select(-value.x, -value.y) %>%
   pivot_wider()

#  Letter check `2011` `2012` `2013`
#  <chr>  <lgl>  <int>  <int>  <int>
#1 A      TRUE       1      2      1
#2 C      FALSE      0     -1      3

data数据

df1 <- structure(list(Letter = c("A", "B", "C"), `2011` = c(2L, 6L,5L),
`2012` = c(3L, 6L, 4L), `2013` = c(5L, 6L, 8L)), row.names = c(NA, -3L), 
class = "data.frame")

df2 <- structure(list(Letter = c("A", "C"), `2011` = c(1L, 5L), `2012` = c(1L, 
5L), `2013` = 4:5), row.names = c(NA, -2L), class = "data.frame")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM