【问题标题】:How to create a new column in R based on what another column starts with如何根据另一列的开头在 R 中创建新列
【发布时间】:2023-02-05 11:32:29
【问题描述】:

我的 df 包含 50 个人的人口统计信息。我的 df 中有一个名为“种族”的专栏,其中包含许多种族类别,包括“英国白人”、“其他白人”和“爱尔兰白人”。我想创建一个新列,其中所有具有这 3 个值之一的观察值都被归类为“白色”,所有不以“白色”开头的观察值都被归类为“POC”。

df %>% mutate(Status = case_when(startsWith(Ethnicity, "White") ~ "White"))

我收到以下错误

Error in `mutate()`:
! Problem while computing `Status = case_when(startsWith(Ethnicity,
  "White") ~ "White")`.
Caused by error in `startsWith()`:
! non-character object(s)
Run `rlang::last_error()` to see where the error occurred.

【问题讨论】:

  • 这不是字符列应该出现的错误,df$Ethnicity 是一个因素吗?您可以通过 str(df$Ethnicity) 查看。或者更好的是,如果您可以共享数据集中的位,请将 dput(head(df)) 的输出添加到您的问题中。

标签: r startswith mutate


【解决方案1】:

请使用adsl dataframe 检查以下代码。
在这里,我将 ETHNICHISPANIC OR LATINONOT HISPANIC OR LATINO 一起使用,我正在创建一个新列,其中所有以 HISP 开头的内容为 HIS,所有其他内容为“NON”,仅作为示例

library(tidyCDISC)
library(tidyverse)

data(adsl,package='tidyCDISC')

adsl %>% select(USUBJID, ETHNIC) %>% 
mutate(new_column=case_when(str_detect(ETHNIC,'^HISPA')==T ~ 'HIP',
                                                            TRUE ~ 'NON'))

创建于 2023-02-04 reprex v2.0.2

# A tibble: 254 × 3
   USUBJID     ETHNIC                 new_column
   <chr>       <chr>                  <chr>     
 1 01-701-1015 HISPANIC OR LATINO     HIP       
 2 01-701-1023 HISPANIC OR LATINO     HIP       
 3 01-701-1028 NOT HISPANIC OR LATINO NON       
 4 01-701-1033 NOT HISPANIC OR LATINO NON       
 5 01-701-1034 NOT HISPANIC OR LATINO NON       
 6 01-701-1047 NOT HISPANIC OR LATINO NON       
 7 01-701-1097 NOT HISPANIC OR LATINO NON       
 8 01-701-1111 NOT HISPANIC OR LATINO NON       
 9 01-701-1115 NOT HISPANIC OR LATINO NON       
10 01-701-1118 NOT HISPANIC OR LATINO NON       
# … with 244 more rows
# ℹ Use `print(n = ...)` to see more rows


【讨论】:

    【解决方案2】:

    我建议不要使用 startsWithstarts_with,而是使用 grepl^ 来指示您要选择所有值从...开始“白色的”。

    library(tidyverse)
    set.seed(123)
    df <- sample(x = c("White Irish", "White British", "Other White"), size = 20, replace = TRUE) %>%
      as.data.frame() %>% rename(Ethnicity = 1)
    
    df %>% mutate(Status = case_when(grepl("^White", Ethnicity) ~ "White", TRUE ~ "Other"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 2021-03-30
      • 2021-12-02
      • 2022-08-19
      • 2020-04-16
      相关资源
      最近更新 更多