1

I have a dataFrame:

V1,V2,V3,V4,V5
1.12331,4.331123,4.12335435,1,"asd"
1.123453345,5.654456,4.889999,1.45456,"qwe"
2.00098,5.5445,4.768799,1.999999,"ttre"

And I want to extract the first column, or all of columns if it's possible, to a string variable.

I'm trying the code below:

library(tidyverse)
td <- read_csv("test.csv")

Convert all the DataFrame to a String

var_text <- toString(td)

But the result is still not what I expect.

[1] "c(1.12331, 1.123453345, 2.00098), c(4.331123, 5.654456, 5.5445), c(4.12335435, 4.889999, 4.768799), c(1, 1.45456, 1.999999)"

I need something like:

strResult = "1.12331, 1.123453345, 2.00098, 4.331123, 5.654456, 5.5445, 4.12335435, 4.889999, 4.768799, 1, 1.45456, 1.999999"
Rui Barradas
  • 44,483
  • 8
  • 22
  • 48

3 Answers3

2

unlist and then convert to string :

toString(unlist(df[-5]))
#[1] "1.12331, 1.123453345, 2.00098, 4.331123, 5.654456, 5.5445, 4.12335435, 4.889999, 4.768799, 1, 1.45456, 1.999999"

Or convert it to a matrix.

toString(as.matrix(df[-5]))

Here, I am excluding the last column since it is not included in the expected output.

Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
  • toString(unlist(td[1:4])) and toString(as.matrix(td[1:4])) Both it works too! Thank you very much! – Bruno Soares Jul 19 '20 at 15:38
  • @BrunoSoares Glad to have been of help! Feel free to [accept the answer](https://stackoverflow.com/help/someone-answers) by clicking on check mark next to vote button on the left if you feel it was useful to you. :-) You can accept only one answer per post. – Ronak Shah Jul 19 '20 at 22:38
1

Try this:

#Data
df <- structure(list(V1 = c(1.12331, 1.123453345, 2.00098), V2 = c(4.331123, 
5.654456, 5.5445), V3 = c(4.12335435, 4.889999, 4.768799), V4 = c(1, 
1.45456, 1.999999), V5 = c("asd", "qwe", "ttre")), row.names = c(NA, 
-3L), class = "data.frame")

#Code
#Create chain
df$chain <- apply(df,1,function(x) paste(x,collapse = ','))
#Now collapse all chain
paste(df$chain,collapse = ',')

[1] "1.123310,4.331123,4.123354,1.000000,asd,1.123453,5.654456,4.889999,1.454560,qwe,2.000980,5.544500,4.768799,1.999999,ttre"
Duck
  • 37,428
  • 12
  • 34
  • 70
0

Try to paste after unlisting the data.frame.

paste(unlist(df[-5]), collapse = ", ")
#[1] "1.12331, 1.123453345, 2.00098, 4.331123, 5.654456, 5.5445, 4.12335435, 4.889999, 4.768799, 1, 1.45456, 1.999999"
Rui Barradas
  • 44,483
  • 8
  • 22
  • 48