简体   繁体   English

将所有行与R数据帧中的特定行进行比较

[英]Compare all rows to one specific row in r dataframe

I would like to know how to most efficiently compare all values in a dataframe to a specific value conditional. 我想知道如何最有效地将数据框中的所有值与特定条件值进行比较。 In this example: 在此示例中:

In this example: 在此示例中:

id <- c("a","a","b","b")
t <- c(2000,2018,2000,2018)
value <- c(10,20,5,30)
test0 <- data.frame(id,value,t,row.names = paste0(id,"_",t))
test  <- test0

which gives: 这使:

       id value    t
a_2000  a    10 2000
a_2018  a    20 2018
b_2000  b     5 2000
b_2018  b    30 2018

I would like to compare values to another id, or another t, or even by row names. 我想将值与另一个id或另一个t甚至行名进行比较。

The best way I found so far was to create a second data frame, containing only the data for id and then joining that column to use it. 到目前为止,我发现的最好方法是创建第二个数据框,仅包含id的数据,然后将其加入该列以使用它。

In this case, the example would be: 在这种情况下,示例为:

tmp <- test0 %>%
  subset(id =="a") %>%
  select(value,t) %>%
  rename(ref=value)

test %>%
  left_join(tmp,by="t") %>%
  mutate(vsRef = value/ref)

which gives: 这使:

  id value    t ref vsRef
1  a    10 2000  10   1.0
2  a    20 2018  20   1.0
3  b     5 2000  10   0.5
4  b    30 2018  20   1.5

I am sure there must be a simple answer, but could not find it easily. 我相信肯定有一个简单的答案,但是很难找到答案。 Could you help? 你能帮忙吗?

Finally found an easy way to do this (when I finally decided to write the post!): 终于找到了一种简单的方法(当我最终决定写这篇文章时!):

test0 %>%
   ddply(.(t),mutate,vsRef=value/value[id=="a"])

  id value    t vsRef
1  a    10 2000   1.0
2  b     5 2000   0.5
3  a    20 2018   1.0
4  b    30 2018   1.5

test0 %>%
   ddply(.(id),mutate,vsRef=value/value[t==2000])

  id value    t vsRef
1  a    10 2000     1
2  a    20 2018     2
3  b     5 2000     1
4  b    30 2018     6

test0 %>%
   mutate(vsRef=value/value[rownames(test0)=="a_2000"])

  id value    t vsRef
1  a    10 2000   1.0
2  a    20 2018   2.0
3  b     5 2000   0.5
4  b    30 2018   3.0

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

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