2017-07-12 198 views
0

我遇到了找到正確的正則表達式以將單列分隔爲兩列的麻煩。使用正則表達式分隔列

這是我的例子。

Col 1 
8.3 algo y algo mas 

我想這

Col 1 Col 2 
8.3  algo y algo mas 

我一直在嘗試此代碼。

library(tidyverse) 
    base <- base %>% 
separate(col 1, into c("col 2", "col 3"), sep = "\\s") 
+0

因此,您的整個前提取決於第1列是非空白值,第2列是剩餘的嗎? – sln

+0

您需要「進入」以獲取與分隔字符串一樣多的名稱。如果你使用「\\ s」,它會將它分成5而不是2. – Kevin

+0

如果你確定列之間會有3個或更多的空格,試試'sep =「\\ s {3,}」'。根據需要調整值。 –

回答

0

爲了安全起見,我認爲這是最好的一個容易識別的字符數後替換每一個空間......

df[, 'Col 1'] <- gsub(pattern = '^([0-9\\.]+) ', replacement = '\\1_', x = df[, 'Col 1'])

然後我會用separate

df <- separate(data = df, col = 'Col 1', into = c('Col 1', 'Col 2'), sep = '_')

我也會改變列名,因爲空間通常是一個問題,當我列名稱...嘗試改爲col_1之類的內容。

+0

謝謝你的回答,但是,有一個問題,當我運行你的代碼時,colums將第一個數字分開。可能是我運行錯了你的代碼。我在這個環境中非常新。 –

+0

是的,我應該注意到,作爲分隔符的點不會很好,因爲你已經有了原始數據中的點。我改變了分隔符,請讓我知道如果這現在適合你。 –

0

您可以從stringrrebus嘗試的功能:

df <- data.frame(Col_1 = "8.3 algo y algo mas") 

library(stringr) 
library(rebus) 
str_match(df$Col_1, pattern = capture(DGT %R% DOT %R% DGT) %R% 
           SPC %R% 
           capture(one_or_more(or(SPC, LOWER)))) 

rebus包允許您使用人類可讀的代碼來構建一塊正則表達式件。輸出結果如下:

#  [,1]     [,2] [,3]    
# [1,] "8.3 algo y algo mas" "8.3" "algo y algo mas" 
+0

謝謝你的回答,這非常有幫助 –