R 如果其他条件保持NA';s
为了得到一个新列,我必须对两列应用条件 对于1和0,我希望第1列中的NA保留为中的NA 新专栏。在R怎么做 这是密码R 如果其他条件保持NA';s,r,if-statement,na,R,If Statement,Na,为了得到一个新列,我必须对两列应用条件 对于1和0,我希望第1列中的NA保留为中的NA 新专栏。在R怎么做 这是密码 df$newcolumn <- ifelse(((df$col1 %in% ("eat")) | (df$col2 %in% ("yes"))), 1, 0) df$newcolumn试试这个。要保留NAs,请添加另一个ifelse,它将检查col1中的NAs并保留它们 df <- structure(list(
df$newcolumn <- ifelse(((df$col1 %in% ("eat")) |
(df$col2 %in% ("yes"))), 1, 0)
df$newcolumn试试这个。要保留NA
s,请添加另一个ifelse
,它将检查col1
中的NA
s并保留它们
df <- structure(list(col1 = c(
NA, "drink", "drink", "drink", "eat",
"eat", "eat", NA, "eat", "drink"
), col2 = c(
"yes", "yes", "no",
"no", "yes", "yes", "yes", "yes", "no", "yes"
), newcolumn = c(
NA,
"1", "0", "0", "1", "1", "1", NA, "1", "1"
)), row.names = c(
NA,
-10L
), class = "data.frame")
df$newcolumn <- ifelse(is.na(df$col1), df$col1, ifelse(df$col1 %in% ("eat") | df$col2 %in% ("yes"), 1, 0))
df
#> col1 col2 newcolumn
#> 1 <NA> yes <NA>
#> 2 drink yes 1
#> 3 drink no 0
#> 4 drink no 0
#> 5 eat yes 1
#> 6 eat yes 1
#> 7 eat yes 1
#> 8 <NA> yes <NA>
#> 9 eat no 1
#> 10 drink yes 1
df 1是
#>2喝是的
#>3喝不到0
#>4.不要喝任何饮料
#>5吃是的
#>6吃是的
#>7吃是的
#>8是的
#>9吃第一
#>10喝是的
您可以尝试:
library(dplyr)
df %>%
mutate(newcolumn = case_when(is.na(col1) ~ NA_integer_,
col1 == 'eat' | col2 == 'yes' ~ 1L,
TRUE ~ 0L))
如果您包含一个简单的示例输入和所需的输出,可以用来测试和验证可能的解决方案,这会更容易帮助您。这使得“是”和“喝”为0,我希望它为1。ifelse(“喝”%in%(“吃”)|“是”%in%(“是”),1,0)
在我的机器上给我一个1。感谢Ronak Shah,我在col2中有“是”和“否”,在新专栏中,我希望“no”和“eat”也为1。以上代码改为0。@a24请不要在注释中扩展问题,请编辑您的问题以包含所需的条件。另外,请阅读有关和如何提供帮助的信息,以便更容易帮助您。