首页 > 解决方案 > 用千位分隔符格式化 tibble 中的数值会产生错误

问题描述

library(tidyverse)

separator <- function(x){
  format(as.numeric(x), big.mark = ".", decimal.mark = ",")
}

x <- c(1000)
y <- c(1000)
z <- c(1000)
df <- tibble(x, y, z)

df[ , 2:ncol(df)] <- apply(df[ , 2:ncol(df)], 2, separator)

错误:

Error: Assigned data `apply(df[, 2:ncol(df)], 2, separator)` must be compatible with existing data.
x Existing data has 1 row.
x Assigned data has 2 rows. 
i Row updates require a list value. Do you need `list()` or `as.list()`? 
Run `rlang::last_error()` to see where the error occurred.

为什么会这样?为什么新数据突然有2行?它应该只保留 1 行并添加千位分隔符,从第二个变量开始到结束。

如果它是 a data.frame,R 不会抱怨,只会完成工作,但不会与tibbles 一起工作。tibble我知道s 和有一些差异data.frames,但我找不到发生这种情况的原因。

编辑(由 Ric S 指出):该代码适用于tibbles,它有不止一行,但不适用于“one-row- tibbles”。

标签: rtibble

解决方案


使用lapply

df[ , 2:ncol(df)] <- lapply(df[ , 2:ncol(df)], separator)

如果您发布了完整的错误/警告消息,那就很清楚了:

# Error: Assigned data `apply(df[, 2:ncol(df)], 2, separator)` must be compatible with existing data.
# x Existing data has 1 row.
# x Assigned data has 2 rows.
# i Row updates require a list value. Do you need `list()` or `as.list()`?
# Run `rlang::last_error()` to see where the error occurred.

然后我们可以检查分配是否兼容,即:列表类:

is.list(apply(df[ , 2:ncol(df)], 2, separator))
# [1] FALSE
is.list(lapply(df[ , 2:ncol(df)], separator))
# [1] TRUE
is.list(df[ , 2:ncol(df)])
# [1] TRUE

推荐阅读