如何控制整数类型列的data.frame中的粘贴行为?

时间:2023-01-04 15:30:17

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?

在第一次应用运行中,R以某种方式知道如何填充额外的空格。它是如何做到的,是否有可能控制这种行为?

1 个解决方案

#1


6  

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.

apply仅适用于数组或矩阵,因此首先必须将data.frame转换为矩阵。 as.matrix(gg)创建填充。

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".

查看as.matrix.data.frame,填充是由格式调用(实际上是format.default)引起的,最终调用了prettyNum。 prettyNum有一个preserve.width参数,默认为“common”。

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

如果您想要更好地控制此行为,请在调用apply之前将data.frame中的每一列转换为字符向量:

gg[,2] <- as.character(gg[,2])
apply(gg,1,paste,collapse="")
# [1] "a1000"   "b100000"

#1


6  

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.

apply仅适用于数组或矩阵,因此首先必须将data.frame转换为矩阵。 as.matrix(gg)创建填充。

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".

查看as.matrix.data.frame,填充是由格式调用(实际上是format.default)引起的,最终调用了prettyNum。 prettyNum有一个preserve.width参数,默认为“common”。

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

如果您想要更好地控制此行为,请在调用apply之前将data.frame中的每一列转换为字符向量:

gg[,2] <- as.character(gg[,2])
apply(gg,1,paste,collapse="")
# [1] "a1000"   "b100000"