将多列粘贴在一起 [英] Paste multiple columns together
本文介绍了将多列粘贴在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在数据框中有一堆列,我想将它们粘贴在一起(用-"分隔),如下所示:
I have a bunch of columns in a dataframe which I want to paste together (seperated by "-") as follows:
data <- data.frame('a' = 1:3,
'b' = c('a','b','c'),
'c' = c('d', 'e', 'f'),
'd' = c('g', 'h', 'i'))
i.e.
a b c d
1 a d g
2 b e h
3 c f i
我想成为谁:
a x
1 a-d-g
2 b-e-h
3 c-f-i
我通常可以这样:
within(data, x <- paste(b,c,d,sep='-'))
,然后删除旧的列,但是不幸的是,我不知道这些列的名称,只是所有列的统称,例如我会知道cols <- c('b','c','d')
and then removing the old columns, but unfortunately I do not know the names of the columns specifically, only a collective name for all of the columns, e.g. I would know that cols <- c('b','c','d')
有人知道这样做的方法吗?
Does anyone know a way of doing this?
推荐答案
# your starting data..
data <- data.frame('a' = 1:3, 'b' = c('a','b','c'), 'c' = c('d', 'e', 'f'), 'd' = c('g', 'h', 'i'))
# columns to paste together
cols <- c( 'b' , 'c' , 'd' )
# create a new column `x` with the three columns collapsed together
data$x <- apply( data[ , cols ] , 1 , paste , collapse = "-" )
# remove the unnecessary columns
data <- data[ , !( names( data ) %in% cols ) ]
这篇关于将多列粘贴在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文