将多列中的值乘以一列中的值 [英] Multiply values in several columns by the values in one column

查看:70
本文介绍了将多列中的值乘以一列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

ID <- c("CB1", "CB2","CB3")
size <- c(10, 40, 4)
Year.1 <- c(10, 6, 15)
Year.2 <- c(12, 7, 20)
Year.3 <- c(14, 8, 25)
data <- data.frame(ID, size, Year.1, Year.2, Year.3)

我想将所有年份的值乘以大小"列中的值(我的实际数据框中有十年).数据最终应该是这样的.

I want to multiply the values for all years, by the values in the 'size' column (I have ten years in my actual data frame). The data should end up looking like this.

ID <- c("CB1", "CB2","CB3")
size <- c(10, 40, 4)
Year.1 <- c(100, 240, 60)
Year.2 <- c(120, 280, 80)
Year.3 <- c(140, 320, 100)
data <- data.frame(ID, size, Year.1, Year.2, Year.3)

理想情况下,新值将替换每年的现有值,因为我真的不想在我的数据框中再添加十列.

Ideally, the new values will replace the existing values for each year, as I don't really want to add another ten columns to my data frame.

推荐答案

lapply 是一个很好的工具.您可以将要相乘的向量、执行乘法的匿名函数以及要乘以的值的附加参数传递给它.

lapply is a good tool here. You can pass it the vectors you want to multiply, an anonymous function that does the multiplication, and an additional argument for the values to multiply by.

ID <- c("CB1", "CB2","CB3")
size <- c(10, 40, 4)
Year.1 <- c(10, 6, 15)
Year.2 <- c(12, 7, 20)
Year.3 <- c(14, 8, 25)
df <- data.frame(ID, size, Year.1, Year.2, Year.3)

df[, paste0("Year.", 1:3)] <- 
  lapply(df[, paste0("Year.", 1:3)],
         function(x, y) x * y,
         y = df$size)

df
   ID size Year.1 Year.2 Year.3
1 CB1   10    100    120    140
2 CB2   40    240    280    320
3 CB3    4     60     80    100

这篇关于将多列中的值乘以一列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆