【问题标题】:Extract words from observations in one column to new columns in R从一列中的观察中提取单词到 R 中的新列
【发布时间】:2022-08-16 22:46:37
【问题描述】:

下面是一个假设的数据框。

Category <- c(\"Male children 0-15 years\", \"Female children 0-15 years\", \"Male Youths 18 years\",  \"Female Youths 18 years\")
value <- c(12, 23, 33, 45)
DF <- data.frame(Category, value)

                   Category value
1   Male children 0-15 years    12
2 Female children 0-15 years    23
3       Male Youths 18 years    33
4     Female Youths 18 years    45

我想将Category 列中的观察分成两个,第一个单词和其余单词,这样我的最终数据框看起来像这样

                    Category gender value          new.column
1   Male children 0-15 years   Male    12 children 0-15 years
2 Female children 0-15 years Female    23 children 0-15 years
3       Male Youths 18 years   Male    33     Youths 18 years
4     Female Youths 18 years Female    45     Youths 18 years

    标签: r gsub stringr


    【解决方案1】:

    使用tidyr::separate

    library(tidyverse)
    DF %>% 
      separate(Category, into = c("gender", "new.column"), remove = FALSE, extra = "merge")
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      相关资源
      最近更新 更多