将列中的行乘以一列

时间:2016-10-17 11:53:27

标签: r dataframe multiplication

我有以下数据:

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)

我希望将所有年份的值乘以&#39; size&#39;中的值。专栏(我的实际数据框中有十年)。数据应该看起来像这样。

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)

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

3 个答案:

答案 0 :(得分:6)

为什么不在基础R中这么简单:

yr <- grep("Year", names(data)) # finds year columns
data[,yr] <- data$size*data[,yr]

#   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

答案 1 :(得分:0)

lapply是一个很好的工具。你可以传递你想要乘法的向量,一个执行乘法的匿名函数,以及一个要乘以的值的附加参数。

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

答案 2 :(得分:0)

dplyr的解决方案:

library("dplyr")
# With dplyr_0.5.0
data %>% mutate_at(.funs = funs(. * size), .cols = vars(contains("Year")))
# or with previous version
data %>% mutate_each_(funs = funs(. * size), vars = vars(contains("Year")))
#    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