如何在mutate语句中对两列进行排序和粘贴? [英] How do you sort and paste two columns in a mutate statement?
本文介绍了如何在mutate语句中对两列进行排序和粘贴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找将两列排序并粘贴到新列中的方法.
I'm looking to sort and paste two columns into a new column.
test = data.frame('a'='jump','b'='jam')
test %>% mutate(new=paste(sort(a,b)))
预期输出是具有三列的数据帧:
expected output is data frame with three columns:
'a'='jump','b'='jam','c'='jamjump'
推荐答案
您必须使用 rowwise
以逐行方式粘贴字符串.
You have to use rowwise
to paste the string in a row-wise fashion.
library(dplyr)
test %>%
rowwise() %>%
mutate(c = paste0(sort(c(a, b)), collapse = ''))
# a b c
# <chr> <chr> <chr>
#1 jump jam jamjump
#2 b a ab
在较大的数据集上,
rowwise
往往会比较慢,为避免使用它,可以在粘贴之前先使用 pmin
/ pmax
对字符串进行排序
rowwise
tend to be slower on larger datasets, to avoid using it you can use pmin
/pmax
to sort the string first before pasting.
test %>%
mutate(col1 = pmin(a, b), col2 = pmax(a, b),
c = paste0(col1, col2)) %>%
select(a, b, c)
数据
test = data.frame('a'=c('jump', 'b'),'b'=c('jam', 'a'))
这篇关于如何在mutate语句中对两列进行排序和粘贴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文