对于R中的循环并通过创建新列附加值

时间:2018-06-12 06:37:18

标签: r

我的数据集如下:

  UID     days
-------|---------
  152  | Monday
  145  | Tuesday
  162  | Thursday
  234  | Sunday

我的数据集UIDdays中有2列。现在,如何在R中创建新列 is_weekday 并循环显示“天”列,如果是工作日,则添加 1 { {1}} 如果是周末。

2 个答案:

答案 0 :(得分:0)

ifelse(grepl("Saturday|Sunday",dat$days),0,1)
[1] 1 1 1 0
> transform(dat,is_weekday=ifelse(grepl("Saturday|Sunday",days),0,1))
  UID     days is_weekday
1 152   Monday          1
2 145  Tuesday          1
3 162 Thursday          1
4 234   Sunday          0

答案 1 :(得分:0)

作为替代方案,这里有一个tidyverse方式

df %>%
    mutate_if(is.factor, as.character) %>%
    mutate(is_weekday = 1 - as.numeric(str_detect("Saturday|Sunday", days)))
#  UID     days is_weekday
#1 152   Monday          1
#2 145  Tuesday          1
#3 162 Thursday          1
#4 234   Sunday          0

样本数据

df <- read.table(text =
    "UID days
152 Monday
145 Tuesday
162 Thursday
234 Sunday", header = T)