【问题标题】:Seperate columns with space用空格分隔列
【发布时间】:2021-09-23 12:53:04
【问题描述】:
df<-separate(df$ALISVERIS_TARIHI, c("key","value")," ", extra=merge)
Error in UseMethod("separate_") : 
  no applicable method for 'separate_' applied to an object of class "character"

“20190901”如何将其分成 3 列,如 2019 09 01?

【问题讨论】:

  • 你查看separate函数的文档了吗?它解释了如何使用它。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: r multiple-columns


【解决方案1】:

如果您想根据字符数分隔第一列,您可以使用extract as -

df <- tidyr::extract(df, ALISVERIS_TARIHI, c('year', 'month', 'day'), '(.{4})(..)(..)')
df

#  year month day a
#1 2019    09  01 a
#2 2019    09  08 b

strcapture 在基础 R 中可以使用相同的模式 -

data <- strcapture('(.{4})(..)(..)', df$ALISVERIS_TARIHI, 
           proto = list(year = integer(), month = integer(), day = integer()))

数据

如果您在reproducible format 中提供数据会更容易提供帮助

df <- data.frame(ALISVERIS_TARIHI = c('20190901', '20190908'), a = c('a', 'b'))

【讨论】:

    【解决方案2】:

    我们可以使用来自base Rread.table

    cbind(read.table(text = as.character(as.Date(df$ALISVERIS_TARIHI,
        format = "%Y%m%d")), sep="-", header = FALSE,
       col.names = c("year", "month", "day")), df['a'])
      year month day a
    1 2019     9   1 a
    2 2019     9   8 b
    

    数据

    df <- structure(list(ALISVERIS_TARIHI = c("20190901", "20190908"), 
        a = c("a", "b")), class = "data.frame", row.names = c(NA, 
    -2L))
    

    【讨论】:

      猜你喜欢
      • 2022-12-26
      • 1970-01-01
      • 2017-08-11
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      相关资源
      最近更新 更多