create a new variable that is the multiplication of an existing variable by a number and that meets a condition

Viewed 305
data <- structure(list(
  x = c(1, 2, 1, 2, 2, 1, 3, 3, 1),
  y = c(20, 30, 40, 10, 15, 34, 57, 72, 12)),
  class = "data.frame",
  row.names = c(NA,-9L))

Hi guys, I want to create a new variable from above data.frame in rstudio but it doesn't work. what I want to do is the same of this command in stata but in rstudio

gen var = y*3600 if x == 1

so I runned this r command but it didn´t work:

df$var[df$x == 1] <- df$y*3600

the new variable should look like this:

x y var
1 20 72000
2 30 NA
1 40 144000
2 10 NA
2 15 NA
1 34 122400
3 57 NA
3 72 NA
1 12 43200

I appreciate any help and thanks in advance

5 Answers
data$var <- ifelse(data$x == 1, data$y * 3600, NA)

  x  y    var
1 1 20  72000
2 2 30     NA
3 1 40 144000
4 2 10     NA
5 2 15     NA
6 1 34 122400
7 3 57     NA
8 3 72     NA
9 1 12  43200

We can use replace like below

> transform(
+   data,
+   var = replace(y * 3600, x != 1, NA)
+ )
  x  y    var
1 1 20  72000
2 2 30     NA
3 1 40 144000
4 2 10     NA
5 2 15     NA
6 1 34 122400
7 3 57     NA
8 3 72     NA
9 1 12  43200

Another option

df$var <- df$y * 3600
df$var[df$x != 1] <- NA

df

#-------
> df
  x  y    var
1 1 20  72000
2 2 30     NA
3 1 40 144000
4 2 10     NA
5 2 15     NA
6 1 34 122400
7 3 57     NA
8 3 72     NA
9 1 12  43200

In data.table

library('data.table')
as.data.table(data)
data[x == 1, var := y*3600]

You need to subset the data from both the ends.

data$var <- NA
data$var[data$x == 1] <- data$y[data$x == 1] *3600
data

#  x  y    var
#1 1 20  72000
#2 2 30     NA
#3 1 40 144000
#4 2 10     NA
#5 2 15     NA
#6 1 34 122400
#7 3 57     NA
#8 3 72     NA
#9 1 12  43200

Another option is to use case_when in dplyr.

library(dplyr)
data <- data %>% mutate(var = case_when(x == 1 ~ y * 3600))

By default if a condition is not satisfied it returns NA.

Related