[英]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.