粘贴三列不等长

时间:2014-02-28 14:48:40

标签: r

假设我有以下数据框,并希望将这三列合并到第四列

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

我可以清理标签列并删除滞后的破折号,但有没有办法在paste()中执行此操作,这样当没有两个或三个值时,我最终没有额外的破折号。

应该是这样的:

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

1 个答案:

答案 0 :(得分: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