Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

paste method for a dataframe

Tags:

r

I would like to input a dataframe into paste and I would like paste to treat it as though I had separately input the columns of that dataframe. The reason I would like to do this is because I'm not sure how many columns my dataframe will have. Here it has 2, but I would like a general solution to deal with any number of columns.

My desired output is test1paste in the following code. But I would like to not have to refer to the columns explicitly. My apply attempt understandably fails because it acts individually on the columns, however I think it gets across the solution I'm looking for.

> test1 <-
+ structure(c(42.71, 41.69, 46.95, 48.85, 45.26, 44.71, 43.71,
+ 42.69, 47.95, 49.85, 46.26, 45.71), .Dim = c(6L, 2L))
>
> test1paste <- paste(test1[,1],test1[,2], sep = "&")
> test1paste
[1] "42.71&43.71" "41.69&42.69" "46.95&47.95" "48.85&49.85" "45.26&46.26"
[6] "44.71&45.71"
>
> apply(test1,MARGIN=2,paste,sep="&")
     [,1]    [,2]
[1,] "42.71" "43.71"
[2,] "41.69" "42.69"
[3,] "46.95" "47.95"
[4,] "48.85" "49.85"
[5,] "45.26" "46.26"
[6,] "44.71" "45.71"

Any ideas?

Thanks!

like image 995
Xu Wang Avatar asked Nov 02 '11 21:11

Xu Wang


1 Answers

How about this :

> apply(test1,1,paste,collapse="&")
[1] "42.71&43.71" "41.69&42.69" "46.95&47.95" "48.85&49.85" "45.26&46.26"
[6] "44.71&45.71"
like image 72
Matt Dowle Avatar answered Oct 26 '22 09:10

Matt Dowle