Thirst for Knowledge - 1 year ago 98

R Question

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?

Answer Source

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)
```