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?
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With