如何將此功能應用于資料框的幾列?
formatC(x, format="f", big.mark = ",", digits=0)
例如應用價格和成本列:
df <- data.frame (origin = c("A","B","C","D","E","F","G","H","I","J"),
price = c(2334235,14545456,345452,74545451,3454545,64545450,1445,2551,4444,6550),
cost = c(10,12,20,2045450,-254545,14545452,14545453,94545450,-104545455,23),
change = c(10,12,-5,12,6,8,0.5,-2,5,-2))
uj5u.com熱心網友回復:
lapply在列上使用回圈。
df <- data.frame (origin = c("A","B","C","D","E","F","G","H","I","J"),
price = c(2334235,14545456,345452,74545451,3454545,64545450,1445,2551,4444,6550),
cost = c(10,12,20,2045450,-254545,14545452,14545453,94545450,-104545455,23),
change = c(10,12,-5,12,6,8,0.5,-2,5,-2))
df[c("price","cost")] <- lapply(df[c("price","cost")], \(x) formatC(x, format="f", big.mark = ",", digits=0))
df
#> origin price cost change
#> 1 A 2,334,235 10 10.0
#> 2 B 14,545,456 12 12.0
#> 3 C 345,452 20 -5.0
#> 4 D 74,545,451 2,045,450 12.0
#> 5 E 3,454,545 -254,545 6.0
#> 6 F 64,545,450 14,545,452 8.0
#> 7 G 1,445 14,545,453 0.5
#> 8 H 2,551 94,545,450 -2.0
#> 9 I 4,444 -104,545,455 5.0
#> 10 J 6,550 23 -2.0
由reprex 包于 2022-06-18 創建(v2.0.1)
或者先定義一個列向量,然后再定義上面的代碼。
cols <- c("price", "cost")
df[cols] <- lapply(df[cols], \(x) formatC(x, format="f", big.mark = ",", digits=0))
結果與上述相同。
該問題也被標記dplyr,這是一個解決方案。
library(dplyr)
df %>%
mutate(across(price:cost, ~ formatC(.x, format="f", big.mark = ",", digits=0)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492608.html
上一篇:如何使用ENTER作為用戶輸入
