2016-11-04 79 views
1

應用str_split的專欄中,我有以下DF名爲I:在數據幀

structure(list(price = c(11772, 14790, 2990, 1499, 21980, 27999 
), fuel = c("diesel", "petrol", "petrol", "diesel", "diesel", 
"petrol"), gearbox = c("manual", "manual", "manual", "manual", 
"automatic", "manual"), colour = c("white", "purple", "yellow", 
"silver", "red", "rising blue metalli"), engine_size = c(1685, 
1199, 998, 1753, 2179, 1984), mileage = c(18839, 7649, 45058, 
126000, 31891, 100), year = c("2013 hyundai ix35", "2016 citroen citroen ds3 cabrio", 
"2007 peugeot 107 hatchback", "2007 ford ford focus hatchback", "2012 jaguar xf saloon", 
"2016 volkswagen scirocco coupe"), doors = c(5, 2, 3, 5, 4, 3 
)), .Names = c("price", "fuel", "gearbox", "colour", "engine_size", 
"mileage", "year", "doors"), row.names = c(NA, 6L), class = "data.frame") 

一些「年」列中的字被複制。我想刪除它們。作爲第一步,我想用單獨的單詞分隔此列中的字符串。 我能做到這一點單獨的字符串,但是當我嘗試將其應用到整個數據幀它給出了一個錯誤

unlist(str_split("2013 hyunday ix35", "[[:blank:]]")) 

[1]「2013」​​「hyunday」,「ix35的」

for(k in 1:nrow(i)) 
+ i[k,7]<-unlist(str_split(i[k, 7], "[[:blank:]]")) 

錯誤[<-.data.frame*tmp*,K,7,值= C( 「2013」​​, 「現代」,: 更換已3行,數據具有1

回答

2

我們可以通過一個或多個空間分開(\\s+ )和paste th Ëunique元素結合在一起通過的list輸出(sapply(..

i$year <- sapply(strsplit(i$year, "\\s+"), function(x) paste(unique(x), collapse=' ')) 
+1

它工作正常。我試圖使用sapply,但不知道如何將兩個功能(粘貼和獨特)結合在一起。 – Vasile

2

dplyrstringr工作(與purrr幫助與列表工作)循環,你可以這樣做:

library(dplyr) 
df %>% 
    mutate(newyear = purrr::map_chr(
    stringr::str_split(year, pattern = "[[:blank:]]"), 
    ~ paste(unique(.x), collapse = " ") 
    )) 
#> price fuel gearbox    colour engine_size mileage 
#> 1 11772 diesel manual    white  1685 18839 
#> 2 14790 petrol manual    purple  1199 7649 
#> 3 2990 petrol manual    yellow   998 45058 
#> 4 1499 diesel manual    silver  1753 126000 
#> 5 21980 diesel automatic     red  2179 31891 
#> 6 27999 petrol manual rising blue metalli  1984  100 
#>        year doors      newyear 
#> 1    2013 hyundai ix35  5    2013 hyundai ix35 
#> 2 2016 citroen citroen ds3 cabrio  2  2016 citroen ds3 cabrio 
#> 3  2007 peugeot 107 hatchback  3  2007 peugeot 107 hatchback 
#> 4 2007 ford ford focus hatchback  5  2007 ford focus hatchback 
#> 5   2012 jaguar xf saloon  4   2012 jaguar xf saloon 
#> 6 2016 volkswagen scirocco coupe  3 2016 volkswagen scirocco coupe 
+0

這太好了。我真的有麻煩了......你能解釋一下'〜粘貼(獨特的......)部分是做什麼的?你知道如何使用它? –