r - 用千位分隔符格式化 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 不会抱怨,只会完成工作,但不会与tibble
s 一起工作。tibble
我知道s 和有一些差异data.frames
,但我找不到发生这种情况的原因。
编辑(由 Ric S 指出):该代码适用于tibble
s,它有不止一行,但不适用于“one-row- tibble
s”。
解决方案
使用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
推荐阅读
- django - 登录后如何使用 LoginRequiredMixin 让 Django 重定向到请求的页面?
- python - 今天开始使用Python,遇到了一个无法真正解决的问题
- go - Golang:在单个选择中使用多个代码案例阻止整个循环
- python - Python将动态值设置为字典
- c# - 如何获取通过 Azure 函数事件中心触发器接收到的事件的 messageId 或 eventId?
- oracle - ADF_FACES-60097
- javascript - 当我在 React.js 中使用 setState 函数时页面重新加载
- c# - 某些服务无法构建。验证服务描述符时出错
- javascript - react-native 应用程序和 RapidAPI - AI 图片着色器
- github-actions - 仅在文件存在时提交