按 R 中的位置提取字符串,最好是 tidyverse

Extracting strings by Position in R, preferably the tidyverse

我有一个数据集如下;

My_data <- tibble(ref = 1:3, codes = c(12204, 35478, 67456))

我想按如下方式分隔 codes 列。

codes列的第一个数字形成一个新变量 clouds

codes列的第二个和第三个数字组成一个新变量wind_direction.

codes列的最后两位组成一个新变量wind_speed

注意:我知道 str_matchstr_match_all 可以做到这一点。问题是他们return一个矩阵。我想要一个将 tibble 扩展为包括三个附加变量的解决方案。

谢谢。

您可以使用 tidyr::extract 函数和适当的正则表达式来进行拆分

My_data %>% 
  mutate(codes = as.character(codes)) %>% 
  extract(codes, c("clouds","wind_direction","wind_speed"), r"{(\d+)(\d{2})(\d{2})}")

#     ref clouds wind_direction wind_speed
#   <int> <chr>  <chr>          <chr>     
# 1     1 1      22             04        
# 2     2 3      54             78        
# 3     3 6      74             56     

另一种选择是使用后续 separate 语句根据位置放入新列(但@MrFlick 的效率更高)。

library(tidyverse)

My_data %>%
  separate(codes, into=c("clouds", "wind_direction"), sep = 1) %>% 
  separate(wind_direction, into=c("wind_direction", "wind_speed"), sep = 2)

或者我们可以在数字之间添加一个分隔符,然后再次使用 separate:

My_data %>%
  mutate(codes = str_replace_all(codes, '^(.{1})(.{2})(.*)$', '\1_\2_\3')) %>% 
  separate(codes, c("clouds","wind_direction","wind_speed"), sep = "_")

输出

    ref clouds wind_direction wind_speed
  <int> <chr>  <chr>          <chr>     
1     1 1      22             04        
2     2 3      54             78        
3     3 6      74             56