首页 > 解决方案 > 在 R 中选择包含特定字符的特定数据(创建另一个变量)

问题描述

我有一个带有时间框架的数据框:

df <- data.frame(start_time = c("30.06.18 19:03", "07.09.19 14:20", "15.06.18 10:42"), stringsAsFactors = FALSE)

我想创建另一个变量来表示它是 2018 年还是 2019 年(1 = 2018 和 2 = 2019)。我试过了...

df$Time <- ifelse(df %>% select(start_time:c(contains(".18"))), 1,
                  ifelse(df %>% select(start_time:c(contains(".19"))), 2, 0))

但我发现选择助手显然只适用于选择变量。所以我有点不知道该怎么做。

提前谢谢了!

标签: rdplyrtidyr

解决方案


Apart from what @MonJeanJean & @Karthik answered, I also found out I could use the grepl function to select specific strings of a character vector.

Anyway, to answer my own question using grepl,

df$Time <- ifelse(grepl(".18", df$start_time), 1,
                  ifelse(grepl(".19", df$start_time), 2, 0))

推荐阅读