English 中文(简体)
• 如何在“演播室”中写案
原标题:How to write case-when-then case in R Studio
  • 时间:2024-02-02 02:10:09
  •  标签:
  • rstudio

例如,我有一个表格。

Field1 Field2 Field3 Field4
1 A Y
2 B Y
3 B N
4 A Y

如果我有一个问询,我写了吗?

Select Case when Field1 = 1 and Field2 = A then Field3 Else Field4 End as NameOfField From Table

问 题:我怎么能用同样的语在RStudio上写同样的问题?

早孕

问题回答

如@tinazmu所建议的,您可使用<代码>case_ when from dplyr#。 你在R.K.的询问相当于:

library(dplyr)

df |> 
  mutate(
    NameOfField = case_when(Field1 == "1" & Field2 == "A" ~ Field3,
                            TRUE ~ Field4)
  )

产出:

#>   Field1 Field2 Field3 Field4 NameOfField
#> 1      1      A      Y   <NA>           Y
#> 2      2      B   <NA>      Y           Y
#> 3      3      B   <NA>      N           N
#> 4      4      A      Y   <NA>        <NA>

此外,由于你的询问只是对一个条件进行检查,我可以建议采用另一个方式,即<条码>。

df |>
  mutate(
    NameOfField = ifelse(Field1 == "1" & Field2 == "A",
                         Field3,
                         Field4)
  )

# output
#>   Field1 Field2 Field3 Field4 NameOfField
#> 1      1      A      Y   <NA>           Y
#> 2      2      B   <NA>      Y           Y
#> 3      3      B   <NA>      N           N
#> 4      4      A      Y   <NA>        <NA>

<>Data:

df <- read.table(text="Field1   Field2  Field3  Field4
1   A   Y   NA
2   B   NA  Y
3   B   NA  N
4   A   Y   NA", header=TRUE, colClasses="character")




相关问题
How to merge monthly datasets side by side?

I have monthly datasets excel files. And I want to combine those files into one. I wanted to see the movement of payments of my customer monthly side by side (see sample table) customer January ...

5.1 %in% seq(0,9, by = 0.01) is FALSE when it should be TRUE

I was trying a seq() function for a loop in R studio and found that I had a problem with it. When I ask : 5.1 %in% seq(0,9, by = 0.01) (or even 0.1) R print FALSE. Only when I print the sequence, 5.1 ...

Rstudio command history

I have been using Rstudio a great deal these days but recently noticed that my commands are not being stored in the history any longer. I don t know then this started, but it might have been with the ...

热门标签