2014-02-28 59 views
1

比方說,我有以下的數據幀,並想過去一起三列到第四列粘貼長度不等的三列

df = data.frame(one=c("honda","ford","kia","bmw"), 
       two=c("subaru","","","lexus"), 
       three=c("","","","ford")) 

我可以用膏把三者結合起來。

df$label = paste(df$one, df$two, df$three, sep=" - ") 
df 

不幸的是,由於數據框中的'空'值,這會導致以下情況。

> df 
    one two three    label 
1 honda subaru  honda - subaru - 
2 ford      ford - - 
3 kia      kia - - 
4 bmw lexus ford bmw - lexus - ford 

我可以清理標籤列,並刪除滯後破折號,但有沒有辦法在粘貼(這樣做),使我最終沒有額外破折號當沒有一個值兩三個。

應該像這樣:

> df 
    one two three    label 
1 honda subaru   honda - subaru 
2 ford       ford 
3 kia       kia 
4 bmw lexus ford bmw - lexus - ford 

回答

4
> df$label <- apply(df, 1, function(x) paste(x[x!=''], collapse=' - ')) 
> df 
    one two three    label 
1 honda subaru   honda - subaru 
2 ford       ford 
3 kia        kia 
4 bmw lexus ford bmw - lexus - ford