简体   繁体   English

如何在 R data.frame 中的多列之间乘以标量值?

[英]How to multiply a scalar value across multiple columns in R data.frame?

I have the following data.frame and i would like to multiply only the numeric columns by a scalar value.我有以下data.frame ,我只想将numeric列乘以scalar量值。

library(tidyverse)
library(lubridate)

set.seed(123)

D1 <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2001-01-10"), by="day"),
                 A1= runif(10,1,5),
                 B2 = runif(10,3,6),
                 C9 = runif(10,2,5))

I tried the following but it eliminate the Date column我尝试了以下但它消除了Date

D <- D1 %>% 
    select(,c(2:4))*1000

Also this one remove the Date column as well.这个也删除了Date列。

D <- D1 %>% 
  select_if(is.numeric)*1000

Are there any option that would keep the Date column and does the multiplication?是否有任何选项可以保留Date列并进行乘法?

I hope this is what you are looking for:我希望这是您正在寻找的:

library(dplyr)

D1 %>%
  mutate(across(where(is.numeric), ~ .x * 1000))

         Date       A1       B2       C9
1  2001-01-01 3915.198 5360.962 3216.361
2  2001-01-02 1984.007 3316.846 4443.792
3  2001-01-03 2888.303 5870.227 4606.728
4  2001-01-04 1955.763 5771.595 3273.241
5  2001-01-05 1533.243 3205.139 3254.499
6  2001-01-06 3129.899 4899.974 3063.600
7  2001-01-07 1873.876 5107.482 4142.117
8  2001-01-08 3807.380 5759.612 2448.172
9  2001-01-09 1396.257 5009.001 4648.551
10 2001-01-10 1280.629 5441.055 4858.487

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM