【问题标题】:Select columns in dplyr conditionally有条件地选择 dplyr 中的列
【发布时间】:2019-03-29 20:39:22
【问题描述】:
library(nycflights13)
library(dplyr)

head(flights)

id.vec <- c("a", "b", "c")

for(i in seq_along(id.vec)){

  id <- id.vec[i]

  temp <- flights %>% dplyr::select(year, day, dep_time, arr_time) %>%
                      dplyr::mutate(year = year - mean(year),
                                    day = day - mean(day),
                                    dep_time = dep_time - mean(dep_time),
                                    arr_time = arr_time - mean(arr_time))

  # do some other tasks with temp file
}

我的问题是我如何设置一个条件,如果id == "c",那么不要 选择dep_time 列,也不要执行dep_time = dep_time - mean(dep_time)

【问题讨论】:

  • 我不确定问题是否相似。反正我去看看
  • 如果只有 3 个 id,那么简单的解决方案是 if else if 等。
  • 其实我有3个以上的id

标签: r select dplyr


【解决方案1】:

一个简单的选择是在 for 循环中包含 if...else... 语句:

for(i in seq_along(id.vec)){


  id <- id.vec[i]

  if(id == 'c') {
  temp <- flights %>% dplyr::select(year, day, arr_time) %>%
    dplyr::mutate(year = year - mean(year),
                  day = day - mean(day),
                  arr_time = arr_time - mean(arr_time))
  } else {
    temp <- flights %>% dplyr::select(year, day, dep_time, arr_time) %>%
      dplyr::mutate(year = year - mean(year),
                    day = day - mean(day),
                    dep_time = dep_time - mean(dep_time),
                    arr_time = arr_time - mean(arr_time))
  }

  # do some other tasks with temp file
}

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 2023-03-10
    • 1970-01-01
    • 2012-10-24
    • 2019-04-20
    • 2020-12-02
    • 2017-07-25
    • 1970-01-01
    • 2016-08-08
    相关资源
    最近更新 更多