簡體   English   中英

R 根據多個條件分配值

[英]R Assign Values based on multiple conditions

我是 R 的新手,我需要新的幫助,根據其他兩個中的條件填充現有列。

數據框稱為 A。

如果列 box=6 AND document = 75 那么 size= big。

我已經嘗試了我在網上找到的多個選項,但 R 一直把它們弄成一個錯誤。 如果有人能給我代碼行,我將不勝感激。 謝謝

沒有更多細節(即可重復的示例),很難知道這是否能回答您的問題,但這里有一個潛在的解決方案:

set.seed(3)
A <- data.frame(box = sample(5:7, size = 50, replace = TRUE),
                document = sample(74:76, size = 50, replace = TRUE))

A$size <- ifelse(A$box == 6 & A$document == 75, "big", "other")
head(A, 10)
#>    box document  size
#> 1    5       76 other
#> 2    6       76 other
#> 3    7       75 other
#> 4    6       75   big
#> 5    7       74 other
#> 6    7       76 other
#> 7    6       75   big
#> 8    7       74 other
#> 9    5       75 other
#> 10   6       74 other

另一個可能的解決方案是使用 dplyr 包中的case_when()

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

A <- data.frame(box = sample(5:7, size = 50, replace = TRUE),
                document = sample(74:76, size = 50, replace = TRUE))
A %>%
  mutate(size = case_when(box == 6 & document == 75 ~ "big",
                          box < 6 & document < 75 ~ "small",
                          document < 75 ~ "medium",
                          TRUE ~ "other"))
#>    box document   size
#> 1    6       75    big
#> 2    6       74 medium
#> 3    7       76  other
#> 4    5       75  other
#> 5    6       76  other
#> 6    5       75  other
#> 7    6       76  other
#> 8    5       74  small
#> 9    5       74  small
#> 10   6       74 medium
#> ...

reprex 包(v2.0.1) 於 2021 年 11 月 8 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM