如何从数字向量中提取前4位数字?

发布于 2025-01-28 11:22:39 字数 197 浏览 3 评论 0原文

game_ID <- c("201600768", "201600842", "201693456", "201700848", "201804567")

我的数据集中有一个列,其中包含许多数字,例如上面的数字。我想从每个数字中提取前4位数字(因为这是游戏发生的一年),然后将它们分成一个新列。

有什么建议吗?

game_ID <- c("201600768", "201600842", "201693456", "201700848", "201804567")

I have a column in my dataset that includes many numbers like the ones above. I would like to extract the first 4 digits from each number(because it is the year the game occurred), and separate them into a new column.

Any suggestions for going about this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁的新欢旧爱 2025-02-04 11:22:39

如果它们始终处于前四个位置,则可以在基本r中使用substr来识别位置:

game_ID <- c("201600768", "201600842", "201693456", "201700848", "201804567")
substr(game_ID, 0, 4)

使用

# [1] "2016" "2016" "2016" "2017" "2018"

如果您的数据是较大数据框中的列,则可以

df <- data.frame(var1 = LETTERS[1:5],
                 var2 = 1:5,
                 game_ID = c("201600768", "201600842", "201693456", "201700848", "201804567"))

:您可以简单地执行此操作。 :

df$year <- substr(df$game_ID, 0, 4)

输出:

#   var1 var2   game_ID year
# 1    A    1 201600768 2016
# 2    B    2 201600842 2016
# 3    C    3 201693456 2016
# 4    D    4 201700848 2017
# 5    E    5 201804567 2018

If they are always in the first four positions, you can use substr in base R to identify the positions:

game_ID <- c("201600768", "201600842", "201693456", "201700848", "201804567")
substr(game_ID, 0, 4)

Output

# [1] "2016" "2016" "2016" "2017" "2018"

If your data are a column in a larger data frame, such as:

df <- data.frame(var1 = LETTERS[1:5],
                 var2 = 1:5,
                 game_ID = c("201600768", "201600842", "201693456", "201700848", "201804567"))

You can simply do this:

df$year <- substr(df$game_ID, 0, 4)

Output:

#   var1 var2   game_ID year
# 1    A    1 201600768 2016
# 2    B    2 201600842 2016
# 3    C    3 201693456 2016
# 4    D    4 201700848 2017
# 5    E    5 201804567 2018
人疚 2025-02-04 11:22:39

使用Stringr软件包到str_extract前4位数字。您可以使用以下代码:

library(dplyr)
library(stringr)
as.data.frame(game_ID) %>%
  mutate(new = str_extract(game_ID, "\\d{4}"))

输出:

    game_ID  new
1 201600768 2016
2 201600842 2016
3 201693456 2016
4 201700848 2017
5 201804567 2018

Using the stringr package to str_extract the first 4 digits. You can use the following code:

library(dplyr)
library(stringr)
as.data.frame(game_ID) %>%
  mutate(new = str_extract(game_ID, "\\d{4}"))

Output:

    game_ID  new
1 201600768 2016
2 201600842 2016
3 201693456 2016
4 201700848 2017
5 201804567 2018
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文