有条件地选择dplyr中的列 [英] Select columns in dplyr conditionally

查看:79
本文介绍了有条件地选择dplyr中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)

My question is how can I put a condition that if id == "c", then do not select the dep_time column and also do not execute the dep_time = dep_time - mean(dep_time)

推荐答案

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

A simple option would be to include an if... else... statement in the for loop:

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
}

这篇关于有条件地选择dplyr中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆