# r - 在 R 中，如何根据条件创建新的变量

``````
a b

1 NA

2 3

3 3

NA 2

NA NA

``````

• `a` 不是 `NA` 时，`b``NA``c = a`

• `a``NA` 时，`b` 不是 `NA``c = b`

• `a``NA` 时，`b``NA``c = NA`

• `a` 不是 `NA` 时，`b` 不是 `NA`，而 `a == b``c = a`

• `a` 不是 `NA` 时，`b` 不是 `NA`，而 `a!= b``c ="multiple_values"`

``````
library(dplyr)

df1 %>%

mutate(c = case_when(!is.na(a) &!is.na(b) & a!= b ~"multiple_values",

TRUE ~ as.character(coalesce(a, b))))

# a b c

#1 1 NA 1

#2 2 3 multiple_values

#3 3 3 3

#4 NA 2 2

#5 NA NA <NA>

``````

### 数据

``````
df1 <- structure(list(a = c(1L, 2L, 3L, NA, NA), b = c(NA, 3L, 3L, 2L,

NA)), class ="data.frame", row.names = c(NA, -5L))

``````

``````
dat <- within(dat, {

c <- NA

c[!is.na(a) & is.na(b)] <- a[!is.na(a) & is.na(b)]

c[is.na(a) &!is.na(b)] <- b[is.na(a) &!is.na(b)]

# # c[is.na(a) & is.na(b)] <- NA # redundant

c[!is.na(a) &!is.na(b) & a == b] <- a[!is.na(a) &!is.na(b) & a == b]

c[!is.na(a) &!is.na(b) & a!= b] <-"multiple_values"

})

dat

# a b c

# 1 1 NA 1

# 2 2 3 multiple_values

# 3 3 3 3

# 4 NA 2 2

# 5 NA NA <NA>

``````

ifelse可以做你想做的事情，但它只是会有很多嵌套语句

``````
df\$c <- with(df, ifelse(!is.na(a) & is.na(b), a,

ifelse(is.na(a) &!is.na(b), b,

ifelse(is.na(a) & is.na(b), NA,

ifelse(!is.na(a) &!is.na(b) & a == b, a,"multiple_values")))))

df

# a b c

#1 1 NA 1

#2 2 3 multiple_values

#3 3 3 3

#4 NA 2 2

#5 NA NA <NA>

``````

``````
df1\$c <-

mapply(function(x, y) {

z <- c(x, y)

z <- unique(z[!is.na(z)])

switch(length(z) + 1L, NA, z,"many")

}, df1\$a, df1\$b)

``````

``````
df1

a b c

1 1 NA 1

2 2 3 many

3 3 3 3

4 NA 2 2

5 NA NA <NA>

``````

``````
df1 <- structure(list(a = c(1L, 2L, 3L, NA, NA), b = c(NA, 3L, 3L, 2L,

NA)), class ="data.frame", row.names = c(NA, -5L))

library(data.table)

df1 <- as.data.table(df1)

df1[, c:="NONE"]

df1[!is.na(a) & is.na(b), c:=a]

df1[is.na(a) &!is.na(b), c:=b]

df1[is.na(a) & is.na(b), c:=NA]

df1[!is.na(a) &!is.na(b) & a==b, c:=a]

df1[!is.na(a) &!is.na(b) & a!=b, c:="multiple values"]

``````