【问题标题】:Splitting numeric column data by given number of characters按给定字符数拆分数字列数据
【发布时间】:2017-06-13 15:05:10
【问题描述】:

我正在尝试将一列拆分为三列,以便提供日期格式。 目前数据集是这样的

YYYYMMDD         Number
20020101         0.21
20020102         0.34
20020103         1.22

我希望它看起来像这样

Year    Month  Day  Number
2002    01     01   0.21
2002    01     02   0.34
2002    01     03   1.22

我编写了以下代码,它的工作原理是我可以拆分列,但是这样做我创建了新的数据框,我不确定如何在 data.frame 中添加回原始数据.set

  • 数据集=数据

有更好的方法吗?或者如何让 new2 + new 与数据结合?

res <- strsplit(data$YYYYMMDD, "(?<=.{4})" , perl = TRUE)
new<-do.call(rbind, res)
summary(new)
colnames(new)<-c("Year", "MMDD")
new<-as.data.frame(new)
new$MMDD<-as.character(new$MMDD)
res <- strsplit(new$MMDD, "(?<=.{2})" , perl = TRUE)
new2<-do.call(rbind, res)
summary(new2)
colnames(new2)<-c("Month", "Dom")
new2<-as.data.frame(new2)

【问题讨论】:

  • 简单的df$Year &lt;- substr(as.character(df$YYYYMMDD), 1,4) 等怎么样?

标签: r strsplit


【解决方案1】:

substring:

x <- mapply(substring, c(1, 5, 7), c(4, 6, 8),
            MoreArgs = list(text = df$YYYYMMDD), SIMPLIFY = F)
names(x) <- c('Year', 'Month', 'Day')
cbind(as.data.frame(x), df[-1])
#   Year Month Day Number
# 1 2002    01  01   0.21
# 2 2002    01  02   0.34
# 3 2002    01  03   1.22

【讨论】:

    【解决方案2】:

    我们可以通过separate轻松做到这一点

    library(tidyr)
    separate(df1, YYYYMMDD, into = c('Year', 'Month', 'Day'), sep=c(4, 6))
    #   Year Month Day Number
    #1 2002    01  01   0.21
    #2 2002    01  02   0.34
    #3 2002    01  03   1.22
    

    【讨论】:

    • 谢谢你,成功了。我不知道我为什么要以如此复杂的方式来处理它
    【解决方案3】:

    你可以试试这个(用你的变量 YYYYMMDD 作为字符):

    year = substr(data$YYYYMMDD,1,4)
    month = substr(data$YYYYMMDD,5,6)
    day = substr(data$YYYYMMDD,7,8)
    
    new_data = as.data.frame(cbind(year,month,day,data$Number))
    colnames(new_data)[4] = "Number"
    

    【讨论】:

      【解决方案4】:

      您可以像这样使用lubridate 进行操作:


      library(tidyverse)
      library(lubridate)
      
      data %>% 
        mutate(
          YYYYMMDD = as.Date(as.character(YYYYMMDD), format = "%Y%m%d"),
          year = year(YYYYMMDD),
          month = month(YYYYMMDD),
          day = mday(YYYYMMDD)
          ) 
      #>     YYYYMMDD Number year month day
      #> 1 2002-01-01   0.21 2002     1   1
      #> 2 2002-01-02   0.34 2002     1   2
      #> 3 2002-01-03   1.22 2002     1   3
      

      【讨论】:

      • 我认为它不会加载library(tidyverse)
      猜你喜欢
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 2017-05-09
      相关资源
      最近更新 更多