R 粘贴三列长度不等的列
假设我有下面的数据框,并希望将这三列合并到第四列中R 粘贴三列长度不等的列,r,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 = 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
> 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