r语言 - 如何使用 tidyR 分隔"."分隔列



我想我错过了一些重要的东西。每次我试图分离一个有"分隔符我失败了。

有人知道为什么吗?

library(tidyverse)
library(reprex)
check=data.frame(time=c("1.2","1.3"),light=c("A","B"))
check
#>   time light
#> 1  1.2     A
#> 2  1.3     B
check %>% 
tidyr::separate(time,c('time2',"node"),sep='.')
#> Warning: Expected 2 pieces. Additional pieces discarded in 2 rows [1, 2].
#>   time2 node light
#> 1                A
#> 2                B

创建于2022-01-06由reprex包(v2.0.1(

对于任何其他分隔符,单独工作都很好,例如

library(tidyverse)
library(reprex)
check=data.frame(time=c("1_2","1_3"),light=c("A","B"))
check
#>   time light
#> 1  1_2     A
#> 2  1_3     B
check %>% 
tidyr::separate(time,c('time2',"node"),sep='_')
#>   time2 node light
#> 1     1    2     A
#> 2     1    3     B

创建于2022-01-06由reprex包(v2.0.1(

sep根据?separate处于正则表达式模式

sep-如果是字符,则sep被解释为正则表达式。默认值是与任何非字母数字值序列匹配的正则表达式。

并且.是根据?regex的元字符

扩展正则表达式中的元字符是。\ |(([{^$*+?,但请注意,这些是否有特殊含义取决于上下文。句点与任何单个字符匹配。

Escape(\(或将其放在方括号([.](内以从字面上评估

library(dplyr)
check %>% 
tidyr::separate(time,c('time2',"node"),sep='\.')

-输出

time2 node light
1     1    2     A
2     1    3     B

最新更新