Thirst for Knowledge
Thirst for Knowledge

Reputation: 1628

R Multiply specific rows and columns by constant

I have the following data:

type <- c(1:4)
year1 <- c(1:4)
year2 <- c(1:4)
year3 <- c(1:4)
data <- data.frame(type, year1, year2, year3)

I want to multiply the bottom two rows within Year columns by two.

type <- c(1:4)
year1 <- c(1, 2, 6, 8)
year2 <- c(1, 2, 6, 8)
year3 <- c(1, 2, 6, 8)
final <- data.frame(type, year1, year2, year3)

How do I do this without affecting the other rows of columns?

Upvotes: 3

Views: 9616

Answers (2)

ulfelder
ulfelder

Reputation: 5335

Here's a solution using dplyr and tidyr. This would allow you to tweak the parameters if you like.

library(dplyr)
library(tidyr)

newdata <- data %>%
  gather(., year, value, year1:year3) %>%
  mutate(newvalue = ifelse(type > 2, value * 2, value)) %>%
  select(-value) %>%
  spread(., year, newvalue)

Upvotes: 3

Mike H.
Mike H.

Reputation: 14370

If you didn't know the length of the data and if you wanted to multiply all columns that have "year" in them you could do:

data[(nrow(data)-1):nrow(data),]<-data[(nrow(data)-1):nrow(data),grep(pattern="year",x=names(data))]*2

  type year1 year2 year3
1    1     1     1     1
2    2     2     2     2
3    6     6     6     6
4    8     8     8     8

Upvotes: 1

Related Questions