1

I have a data.frame that is manually created like:

a = data.frame(a = c(1,3,4), b = c(1,3,4))
> a
  a b
1 1 1
2 3 3
3 4 4

I want to convert the elements in the data.frame to string, but I got this:

> toString(a)
[1] "c(1, 3, 4), c(1, 3, 4)"

anyone helps?

a similar question has been asked and answered, so we probably can change the question to why toString does not work properly on data.frame?

And the accepted answer gives some clue...

Xin Niu
  • 533
  • 1
  • 5
  • 15

3 Answers3

2

If we want to do this on each column, loop over the columns with sapply/lapply and apply the toString

sapply(a, toString)

If the OP wanted to convert the columns to character class we can use lapply in base R

a[] <- lapply(a, as.character)

toString is paste(..., collapse=", ") and paste converts its arguments via as.character to character strings, but as.character calls as.vector and it is calling on the data.frame directly and which cause this issue

akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can use the across function from dplyr package, to apply a function in every column of your data.frame. In your case, you can convert all of your data to characters using the as.character() function.

library(dplyr)

a <- mutate(a, across(.fns = as.character))

str(a)

'data.frame':   3 obs. of  2 variables:
 $ a: chr  "1" "3" "4"
 $ b: chr  "1" "3" "4"
Pedro Faria
  • 707
  • 3
  • 7
1

Is this what you want?

library(dplyr)

a %>%
  mutate(across(everything(), as.character)) %>% as_tibble()
# A tibble: 3 x 2
  a     b    
  <chr> <chr>
1 1     1    
2 3     3    
3 4     4  

Or is this?

a %>%
  summarise(across(everything(), toString)) %>% as_tibble()
# A tibble: 1 x 2
  a       b      
  <chr>   <chr>  
1 1, 3, 4 1, 3, 4
Ben Norris
  • 5,639
  • 2
  • 6
  • 15