[英]How to apply function to several columns in R?
如何將此功能應用於數據框的幾列?
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))
在列上使用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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.