【问题标题】:splitting strings into columns in R将字符串拆分为R中的列
【发布时间】:2019-12-23 21:28:06
【问题描述】:

我在 R 数据框中有一个带有文本的向量,如下所示:

string<-c("Real estate surface: 60m2 Number of rooms: 3 Number of bedrooms: 2 Number of bathrooms: 1 Number of toilets: 0 Year of construction: 1980 Last renovation: Floor: 1/15")

并且我想将文本拆分为具有关联值的 8 列数据框,例如

我该怎么做? 谢谢!

【问题讨论】:

  • Last renovation之后是空的吗
  • 是的。缺失值
  • 你尝试过什么,你在哪里卡住了?

标签: r text split stringr


【解决方案1】:

一种选择是为缺失的情况创建NA,然后使用separate_rows/separate 来拆分字符串

library(dplyr)
library(tidyr)
library(stringr)
library(tibble)
tibble(col = string) %>%
   mutate(col = str_replace_all(col, ": (?![0-9])", ": NA ")) %>% 
   separate_rows(col, sep="(?<=:\\s\\w{1,5}) ") %>%
   separate(col, into = c('col1', 'col2'), sep=":\\s+") %>% 
   deframe %>% 
   as.data.frame.list(check.names = FALSE) %>%
   type.convert(as.is = TRUE)
#Real estate surface Number of rooms Number of bedrooms Number of bathrooms Number of toilets Year of construction
#1             60m2               3                  2                   1                 0                 1980
#  Last renovation Floor
#1              NA  1/15

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 1970-01-01
    • 2021-03-07
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多