Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste data frame without changing into factor levels

Tags:

dataframe

r

paste

I have vectors let say a,b,c,d as below:

 a <- c(1,2,3,4)
 b <- c("L","L","F","L")
 c <- c(11,22,33,44)
 d <- c("Y", "N", "Y","Y")

And I try to use paste to get this output (1):

paste(a,b,c,d, sep = "$", collapse = "%")
[1] "1$L$11$Y%2$L$22$N%3$F$33$Y%4$L$44$Y"

Then I change it into this, let say df:

df <- data.frame(a,b,c,d)

and get this output (2):

paste(df, sep = "$", collapse = "%")
[1] "c(1, 2, 3, 4)%c(2, 2, 1, 2)%c(11, 22, 33, 44)%c(2, 1, 2, 2)"

My question is: (1) Can somebody explain to me why in df it change its elements into numeric? (2) Is there any other way that I can use df to get output (1)?

like image 694
mojek Avatar asked Jun 25 '26 23:06

mojek


2 Answers

paste runs as.character (or something similar internally) on its ... arguments, effectively deparsing the list. Have a look at

as.character(df)
# [1] "c(1, 2, 3, 4)"     "c(2, 2, 1, 2)"     "c(11, 22, 33, 44)" "c(2, 1, 2, 2)"    
deparse(df$a)
# [1] "c(1, 2, 3, 4)"

Your code is pasting these values together. To get around this, you can use do.call.

do.call(paste, c(df, sep = "$", collapse = "%"))
# [1] "1$L$11$Y%2$L$22$N%3$F$33$Y%4$L$44$Y"
like image 197
Rich Scriven Avatar answered Jun 28 '26 12:06

Rich Scriven


Here is an alternative to the approach you used:

df_call <- c(df, sep="$")
paste(do.call(paste, df_call), collapse="%")

[1] "1$L$11$Y%2$L$22$N%3$F$33$Y%4$L$44$Y"

Demo

like image 26
Tim Biegeleisen Avatar answered Jun 28 '26 11:06

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!