我试图添加数千分隔符到某些列值。在这个例子中,列x2和x1,但是我没有这样做。下面是我的代码:
my_data <- data.frame(x1 = c("a","b", "c"),
x2 = c(10000, 5000, 5000),
x3 = 1001:1003)
col_conv <- c("x3","x2")
my_data_updated <- my_data
my_data_updated[ , col_conv] <- lapply(my_data_updated[ , col_conv],
function(x){ as.numeric(gsub(",", "", x)) })
数据帧格式没有改变
谢谢
要做到这一点,您必须创建自己的类:
在这里和这里检查这些解决方案和解释
在你的例子中,写这四个函数:
my_numbers <- function(x) structure(x, class = c('my_numbers', 'numeric'))
format.my_numbers <- function(x,...)NextMethod(sci = FALSE, big.mark=',')
print.my_numbers <- function(x,...) print(format(x), quote = FALSE)
'[.my_numbers' <- function(x,...,drop = FALSE) my_numbers(NextMethod('['))
现在运行:
x <- my_numbers(c(1000000, 1000, 20003))
x
[1] 1,000,000 1,000 20,003
你可以在x
上做数学:
x * 2
[1] 2,000,000 2,000 40,006
现在输入data.frame:
my_data[c('x2', 'x3')] <- lapply(my_data[c('x2', 'x3')], my_numbers)
my_data
x1 x2 x3
1 a 10,000 1,001
2 b 5,000 1,002
3 c 5,000 1,003
试试这个
my_data_result<-my_data%>%
mutate(across(x2:x3, ~formatC(., format="d", big.mark=",")))