【问题标题】:Split string in data.frame data.table into two columns with Base R使用 Base R 将 data.frame data.table 中的字符串拆分为两列
【发布时间】:2020-08-29 22:39:41
【问题描述】:

如何使用 Base R 将列 rn 拆分为两列? 我尝试了strsplit(schluempfe$rn, ".", fixed=TRUE),它成功拆分,但我不知道如何使用此函数获取两列。我需要用 cbind() 将它们绑定回来吗? 如果这不可能,我将恢复为单独()或 str_split_fixed(),但对于 Base R 来说“似乎足够简单”。

> str(schluempfe)
Classes ‘data.table’ and 'data.frame':  13534 obs. of  2 variables:
 $ rn    : chr  "oberschlumpf.2020-05-13" "oberschlumpf.2020-05-12" 
"oberschlumpf.2020-05-11" "oberschlumpf.2020-05-10" ...
 $ reCNru: num  15.9 19.2 25.2 21.3 18.6 ...
 - attr(*, ".internal.selfref")=<externalptr> 

作为我想看到的输出

Classes ‘data.table’ and 'data.frame':  13534 obs. of  3 variables:
 $ rn1   : chr  "oberschlumpf" "oberschlumpf" "oberschlumpf" "oberschlumpf" ...
 $ rn2   : chr  "2020-05-130" "2020-05-12" "2020-05-11" "2020-05-10" ...
 $ reCNru: num  15.9 19.2 25.2 21.3 18.6 ...
 - attr(*, ".internal.selfref")=<externalptr> 

【问题讨论】:

标签: r strsplit


【解决方案1】:

首先,我们需要一些样本数据,取自您发布的内容:

dataset <- data.frame(reCNru = c(15.9, 19.2, 25.2, 21.3),
                      rn = c("oberschlumpf.2020-05-13", "oberschlumpf.2020-05-12", 
                             "oberschlumpf.2020-05-11", "oberschlumpf.2020-05-10"), 
                      stringsAsFactors = FALSE)

然后我们在 Base R 中应用以下代码:

newdataset <- setNames(do.call(rbind.data.frame, strsplit(unlist(dataset$rn), '\\.')), 
         c('rn1', 'rn2')) 
newdataset$reCNru <- dataset$reCNru

也许看看tidyverse给出的解决方案很有趣:

dataset %>% tidyr::separate(col = rn, into = c("rn1","rn2"), sep = "\\.")

你将拥有:

reCNru          rn1        rn2
1   15.9 oberschlumpf 2020-05-13
2   19.2 oberschlumpf 2020-05-12
3   25.2 oberschlumpf 2020-05-11
4   21.3 oberschlumpf 2020-05-10

请注意,分隔符不仅仅是".",而是一个表示点的表达式。

希望对你有帮助。

【讨论】:

  • Separate 将参数 sep 作为正则表达式,但 . 表示“任何字符”,因此您可以使用 \\. 对其进行转义
猜你喜欢
  • 1970-01-01
  • 2015-01-22
  • 2021-12-28
  • 1970-01-01
  • 2020-06-18
  • 2020-01-19
  • 1970-01-01
  • 2019-08-30
  • 2017-10-01
相关资源
最近更新 更多