【问题标题】:check if values in a series of columns are within a certain number of values from those in another series of columns检查一系列列中的值是否在另一列列中的一定数量的值范围内
【发布时间】:2019-07-09 17:10:15
【问题描述】:

我在 R 中有一个如下所示的数据框:

|---------------------------------------------------------|
| col1 | col2   | col3  | col4  | col5  | col6   | col7   |
|______|________|_______|_______|_______|________|________|
| x    | 2003   | 2004  | 2009  | 2002  | 2011   | NA     |
|------|--------|-------|-------|-------|--------|--------|
| y    | 2004   |  NA   | NA    | 2002  | 2004   | NA     |
|------|--------|-------|-------|-------|--------|--------|
| x    | 2007   |  2009 | NA    | 2010  | 2012   | 2013   |
|---------------------------------------------------------|

我想检查 col1 中每个类别的次数,col5:col7 中的值在 (0-2) col2:col4 中的任何值之后的 2 年或更少年内出现。

所以想要的结果是这样的:

[[x]] 
2
[[y]]
1

或者像这样的数据框:

col1 | count |
______________
x    | 2
--------------
y    | 1

我认为必须有一种 dplyr 方法来做到这一点? 像gather()filter() 的东西? 或者使用sapply 获取值之间的差异然后只计算数字> 2 的某种方法?

我遇到的主要问题是,当并非所有列都有每一行的值时的语法,我想将 col2:col4 中的值与 col5:col7 中的所有值进行比较,而不仅仅是一个特定的列。

【问题讨论】:

  • 也许gathergroup_by col1 和计数?
  • 不,应该在 col2:col4 的 0-2 年范围内。刚刚编辑以使其更清晰

标签: r dplyr apply


【解决方案1】:

好的,谢谢@NelsonGon 这行得通,但我认为可能有更简单的方法:

#convert to long format
test <- mydf %>%
  gather( first_group, year.1, col2:col4) %>%
  gather(scond_group, year.2, col5:col7) 

#remove the NA values
test <- test[-c(which(is.na(test$year.2))),]
test <- test[-c(which(is.na(test$year.1))),]

#count number fitting criteria
test2 <- test %>%
  group_by(col1) %>%
  filter(year.2 >= year.1 & year.2 <= year.1 + 2) %>%
  summarise(n = n()) 

##result
#test1
## A tibble: 2 x 2
#depend_var     n
#<chr>      <int>
#1 x         2
#2 y         1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多