Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R: Joining vector elements by row, converting vector rows to strings

Tags:

r

Is there a "by row" operation in R to convert each row in a vector like this to strings?

> d= cbind("Data", c("2", "73"))
> d
     [,1]   [,2]
[1,] "Data" "2" 
[2,] "Data" "73"

What I want is to get strings like

     [,1]
[1,] "Data 2"
[2,] "Data 73"

Is there an easy way to join items by row?

like image 440
gakera Avatar asked Nov 18 '10 10:11

gakera


People also ask

How do I convert a row to a vector in R?

If we want to turn a dataframe row into a character vector then we can use as. character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.

How do I turn a list into a string in R?

1. Using paste() to Convert List to String. The paste() function in R can be used to convert or merge a list of elements into a string by separating each element by a delimiter. To separate the string elements from a single list using the collapse param with the delimiter.

How do I turn a row into a list in R?

We can convert a given data frame to a list by row we use the split() function. The split() function is used to split the data according to our requirement and the arguments given in the split() function are data itself and the other one is seq() function.

How do I convert a string to a vector in R?

Convert elements of a Vector to Strings in R Language – toString() Function. toString() function in R Programming Language is used to produce a single character string describing an R object. Parameters: x: R object.


2 Answers

Yes, there is. It is called "apply" ;-)

apply(d,1,paste,collapse=" ")
[1] "Data 2"  "Data 73"
# convert to matrix using as.matrix to get exactly your solution

See ?apply and ?paste

like image 178
Joris Meys Avatar answered Sep 19 '22 13:09

Joris Meys


A general way to do it without resorting to ?apply:

do.call(paste, as.data.frame(d))
[1] "Data 2"  "Data 73"

Where as.data.frame is used to avoid subscripts.

Edit:

do.call is a function which takes another function as first argument, and a list as second argument. It is often used to send lists of arguments to functions (in our case, the columns of d to paste()). We send d as a data.frame (a type of list) for this trick to work.

like image 23
Beginning_Math Avatar answered Sep 20 '22 13:09

Beginning_Math