Reputation: 10597
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!
Upvotes: 11
Views: 12510
Reputation: 40821
If your "dataframe" is actually a data.frame
(and not a matrix
as in your example), you could use do.call
directly:
testdf <- as.data.frame(test1)
do.call(paste, c(testdf, sep="&"))
This relies on the fact that a data.frame
is a glorified list
, and do.call
takes a list of arguments. I just append the sep
argument to the list...
Small caveat though: if any column name is "sep" or "collapse" you could be in trouble. Removing the column names would help in that case:
do.call(paste, c(unname(testdf), sep="&"))
Upvotes: 9
Reputation: 59602
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"
Upvotes: 9