繁体   English   中英

比较 R 中的两个数据帧

[英]Compare two dataframes in R

我在 R 中有两个数据框,想比较行的任何条目。 我想要两次检查第一个数据帧的第一(任何)行的第一个条目、第二个条目等的值是否大于第二个数据帧的第一行的第一个条目的条目。 之后,如果所有条目都更大并且在间隔 (0,2) 中,它应该给我一个 TRUE。 它看起来像这样。

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.

一种方法可能是将数据转换为长格式,执行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

数据

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