Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control paste behaviour in data.frame for integer type columns?

Tags:

r

Here is the sample code, which produces interesting output:

> gg<-data.frame(x=c("a","b"),y=as.integer(c(1000,100000)))
> gg
  x      y
1 a   1000
2 b 100000
> apply(gg,1,paste,collapse="")
[1] "a  1000" "b100000"
> apply(gg[1,],1,paste,collapse="")
      1 
"a1000" 

In the first apply run, R somehow knows how to pad additional spaces. How does it do that and is it possible to control this behaviour?

like image 733
mpiktas Avatar asked Apr 02 '12 11:04

mpiktas


Video Answer


1 Answers

apply only works on an array or matrix, so it first has to convert your data.frame to a matrix. as.matrix(gg) creates the padding.

Looking at as.matrix.data.frame, the padding is caused by a call to format (format.default, actually), which eventually calls prettyNum. prettyNum has a preserve.width argument with a default of "common".

If you want more control over this behavior, convert each column in your data.frame to a character vector before calling apply:

gg[,2] <- as.character(gg[,2])
apply(gg,1,paste,collapse="")
# [1] "a1000"   "b100000"
like image 75
Joshua Ulrich Avatar answered Oct 17 '22 06:10

Joshua Ulrich