我的数据集如下:
UID days
-------|---------
152 | Monday
145 | Tuesday
162 | Thursday
234 | Sunday
我的数据集UID
和days
中有2列。现在,如何在R中创建新列 is_weekday
并循环显示“天”列,如果是工作日,则添加 1
{ {1}} 如果是周末。
答案 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)