为什么as.matrix在将数字转换为字符时会添加额外的空格?

fls*_*std 30 r

如果在带有字符和数字列的data.frame上使用apply over rows,则apply会在内部使用as.matrix将data.frame转换为仅字符.但如果数字列由不同长度的数字组成,则.matrix会添加空格以匹配最高/"最长"数字.

一个例子:

df <- data.frame(id1=c(rep("a",3)),id2=c(100,90,8), stringsAsFactors = FALSE) 
df
##   id1 id2
## 1   a 100
## 2   a  90
## 3   a   8
as.matrix(df)
##      id1 id2  
## [1,] "a" "100"
## [2,] "a" " 90"
## [3,] "a" "  8"
Run Code Online (Sandbox Code Playgroud)

我原以为结果是:

     id1 id2  
[1,] "a" "100"
[2,] "a" "90"
[3,] "a" "8"
Run Code Online (Sandbox Code Playgroud)

为什么多余的空间?

在data.frame上使用apply时,它们可能会产生意外的结果:

myfunc <- function(row){
  paste(row[1], row[2], sep = "")
}
> apply(df, 1, myfunc)
[1] "a100" "a 90" "a  8"
> 
Run Code Online (Sandbox Code Playgroud)

虽然循环给出了预期的结果.

> for (i in 1:nrow(df)){
  print(myfunc(df[i,]))
}
[1] "a100"
[1] "a90"
[1] "a8"
Run Code Online (Sandbox Code Playgroud)

> paste(df[,1], df[,2], sep = "")
[1] "a100" "a90"  "a8"  
Run Code Online (Sandbox Code Playgroud)

是否有任何情况下使用as.matrix添加的额外空格是有用的?

Rei*_*son 23

这是因为在方法中转换非数字数据的as.matrix.data.frame方式.有一个简单的解决方法,如下所示.

细节

?as.matrix注意转换是通过format(),并在这里添加额外的空格.具体来说,?as.matrix详细信息部分中有这个:

 ‘as.matrix’ is a generic function.  The method for data frames
 will return a character matrix if there is only atomic columns and
 any non-(numeric/logical/complex) column, applying ‘as.vector’ to
 factors and ‘format’ to other non-character columns.  Otherwise,
 the usual coercion hierarchy (logical < integer < double <
 complex) will be used, e.g., all-logical data frames will be
 coerced to a logical matrix, mixed logical-integer will give a
 integer matrix, etc.
Run Code Online (Sandbox Code Playgroud)

?format 还注意到

字符串用空白填充到最宽的显示宽度.

考虑这个示例来说明行为

> format(df[,2])
[1] "100" " 90" "  8"
> nchar(format(df[,2]))
[1] 3 3 3
Run Code Online (Sandbox Code Playgroud)

format具备这样的工作方式,因为它有trim:

trim: logical; if ‘FALSE’, logical, numeric and complex values are
      right-justified to a common width: if ‘TRUE’ the leading
      blanks for justification are suppressed.
Run Code Online (Sandbox Code Playgroud)

例如

> format(df[,2], trim = TRUE)
[1] "100" "90"  "8"
Run Code Online (Sandbox Code Playgroud)

但是没有办法将这个参数传递给as.matrix.data.frame方法.

解决方法

解决这个问题的一种方法是format()通过手动方式自行应用sapply.在那里你可以通过trim = TRUE

> sapply(df, format, trim = TRUE)
     id1 id2  
[1,] "a" "100"
[2,] "a" "90" 
[3,] "a" "8"
Run Code Online (Sandbox Code Playgroud)

或者,使用vapply我们可以说明我们期望返回的内容(这里是长度为3 [ nrow(df)]的字符向量):

> vapply(df, format, FUN.VALUE = character(nrow(df)), trim = TRUE)
     id1 id2  
[1,] "a" "100"
[2,] "a" "90" 
[3,] "a" "8"
Run Code Online (Sandbox Code Playgroud)


nog*_*pes 9

这看起来有点奇怪.在手册(?as.matrix)中解释了format要求转换为字符矩阵:

如果只有原子列和任何非(数字/逻辑/复杂)列,将as.vector应用于因子并格式化为其他非字符列,则数据帧的方法将返回字符矩阵.

你可以看到,如果你format直接打电话,它会做什么as.matrix:

format(df$id2)
[1] "100" " 90" "  8"
Run Code Online (Sandbox Code Playgroud)

你需要做的是通过trim调整:

format(df$id2,trim=TRUE)
[1] "100" "90"  "8" 
Run Code Online (Sandbox Code Playgroud)

但是,遗憾的是,该as.matrix.data.frame功能不允许您这样做.

else if (non.numeric) {
    for (j in pseq) {
        if (is.character(X[[j]])) 
            next
        xj <- X[[j]]
        miss <- is.na(xj)
        xj <- if (length(levels(xj))) 
            as.vector(xj)
        else format(xj) # This could have ... as an argument
        # else format(xj,...)
        is.na(xj) <- miss
        X[[j]] <- xj
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,你可以修改as.data.frame.matrix.但是,我认为这将是一个很好的功能添加,但是,将它包含在基础中.

但是,一个快速的解决方案就是:

as.matrix(data.frame(lapply(df,as.character)))
     id1 id2  
[1,] "a" "100"
[2,] "a" "90" 
[3,] "a" "8"  
# As mentioned in the comments, this also works:
sapply(df,as.character)
Run Code Online (Sandbox Code Playgroud)


EDi*_*EDi 6

as.matrixformat内部呼叫:

 > format(df$id2)
[1] "100" " 90" "  8"
Run Code Online (Sandbox Code Playgroud)

这就是额外空间的来源.format有一个额外的参数trim来删除那些:

> format(df$id2, trim = TRUE)
[1] "100" "90"  "8"  
Run Code Online (Sandbox Code Playgroud)

但是你不能提供这个参数as.matrix.