【问题标题】:How to change ordered group of columns, whose names lie within range of values?如何更改名称在值范围内的有序列组?
【发布时间】:2018-08-02 17:45:54
【问题描述】:

我正在使用以下数据框,其中包含 1997-2010 年每一年的列变量数据,以及由列“min”和“max”描述的年份范围。

如果年份在最小值到最大值的范围内,我希望将每一年列中的值更改为 1。我该怎么做?

library(tidyverse)

    df <- structure(list(`1997` = c(1, 0, 0, 0, 0, 0), `1998` = c(0, 0, 
0, 0, 0, 0), `1999` = c(0, 0, 0, 0, 0, 0), `2000` = c(0, 0, 0, 
1, 0, 1), `2001` = c(0, 0, 0, 1, 0, 1), `2002` = c(0, 0, 0, 0, 
0, 1), `2003` = c(0, 0, 0, 0, 0, 1), `2004` = c(0, 0, 0, 0, 0, 
1), `2005` = c(0, 0, 0, 1, 0, 1), `2006` = c(0, 0, 1, 0, 0, 1
), `2007` = c(0, 0, 1, 1, 0, 1), `2008` = c(0, 0, 1, 1, 0, 1), 
    `2009` = c(0, 0, 1, 1, 0, 1), `2010` = c(0, 0, 1, 1, 0, 1
    ), min = c(1997, 1998, 2006, 2000, 1997, 2000), max = c(1998, 
    1998, 2010, 2010, 2008, 2010)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"), .Names = c("1997", "1998", "1999", "2000", 
"2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", 
"2009", "2010", "min", "max"))

我尝试使用 dplyr 包中的 mutate_at 并创建一个向量来分配给这些列(并稍后进行操作),但我在这个角度上苦苦挣扎。我应该如何将以下调用更改为funs(),以便我可以将该范围内的所有 0 更改为 1?

 for (i in 1:nrow(df)){
    if (!is.na(df[i,]$min) & !is.na(df[i,]$max)){
      df[i,] <- df[i,] %>% 
        mutate_at(vars(`1997`:`2010`), funs(min:max))
    }
  } 

【问题讨论】:

  • 有趣的问题。我希望你不会介意最终的 data.frame 显示 TRUE/FALSE 而不是 1/0

标签: r dplyr


【解决方案1】:

一种解决方案可能是使用sapplymapply,如下所示。我还使用了来自dplyrbetween 函数。

我的解决方案显示FALSE/TRUE,而不是01。希望 OP 没问题。

#df has been taken from OP
sapply(names(df)[1:(ncol(df)-2)], 
      function(x)mapply(between, as.numeric(x), df$min, df$max)) %>%
       as.data.frame() %>% cbind(df[,c("min","max")])

   1997  1998  1999  2000  2001  2002  2003  2004  2005  2006  2007  2008  2009  2010  min  max
1  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 1997 1998
2 FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 1998 1998
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE 2006 2010
4 FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE 2000 2010
5  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE 1997 2008
6 FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE 2000 2010

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 2020-08-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2011-07-19
    相关资源
    最近更新 更多