Reputation: 1628
I have the following data:
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.
Upvotes: 1
Views: 3665
Reputation: 12937
Why not this simple in base 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
Upvotes: 10
Reputation: 13856
A solution with 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
Upvotes: 1
Reputation: 17369
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
Upvotes: 1