简体   繁体   中英

gen new variable conditionally equal old variable in r

I want to conditionally create a new var = old var. My data looks like this:

      id id2
1.1    1   1
1.2    2   2
1.3    3   3
1.4    4   4
1.5   NA   5
5.5    5   6
5.6    6   7
5.7    7   8
5.8    8   9
5.51  NA  10
9.9    9  11
9.10  10  12
9.11  11  13
9.4   NA  14
12.12 12  15
12.2  NA  16
13.13 13  17
13.14 14  18
13.15 15  19
13.16 16  20

How can I create a new var = id2 when id is missing? If id is not missing, id3 is missing.

      id id2 id3
1.1    1   1
1.2    2   2
1.3    3   3
1.4    4   4
1.5   NA   5 5
5.5    5   6
5.6    6   7
5.7    7   8
5.8    8   9
5.51  NA  10 10
9.9    9  11
9.10  10  12
9.11  11  13
9.4   NA  14 14
12.12 12  15
12.2  NA  16 16
13.13 13  17
13.14 14  18
13.15 15  19
13.16 16  20

Thanks!!

Assuming that dat is your data frame, you can do the following based on ifelse in base R.

dat$id3 <- with(dat, ifelse(is.na(id), id2, NA))

Or

dat2 <- transform(dat, id3 = ifelse(is.na(id), id2, NA))

DATA

dat <- read.table(text = "      id id2
1.1    1   1
                  1.2    2   2
                  1.3    3   3
                  1.4    4   4
                  1.5   NA   5
                  5.5    5   6
                  5.6    6   7
                  5.7    7   8
                  5.8    8   9
                  5.51  NA  10
                  9.9    9  11
                  9.10  10  12
                  9.11  11  13
                  9.4   NA  14
                  12.12 12  15
                  12.2  NA  16
                  13.13 13  17
                  13.14 14  18
                  13.15 15  19
                  13.16 16  20", 
                  header = TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM