r - 在 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))
但我发现选择助手显然只适用于选择变量。所以我有点不知道该怎么做。
提前谢谢了!
解决方案
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))
推荐阅读
- php - Share URL including URL parameter through Facebook
- reactjs - 在反应组件上使用 Laravel 项目 CSS
- c# - 运行总 C#
- python - 将列表中的元素弹出到列表中 [Python 3.x]
- webrtc - 如何使用 SimpleWebRTC 错误创建视频聊天应用程序网络
- powerbi - 具有自动刷新功能的 Power BI DirectQuery 报表
- css - 如何在 CSS 中制作离散宽度?
- wordpress - 优先顺序如何影响 WordPress 中的 add_action 和 do_action 链?
- c++ - 在 C++ 中放置派生的新基础子对象
- ios - What does .text actually do to a value?