【问题标题】:R transform data frame columns into single column based on column name splitR根据列名拆分将数据框列转换为单列
【发布时间】:2020-04-04 19:17:58
【问题描述】:

一个常见的数据清理问题,但我在执行时遇到了一些麻烦。

我有一个包含多列 year.month 信息的数据集,如下所示:

    loc      type  2010.01  2010.02  2010.03 
  Manhattan   a      2300     2300     2500     
  Manhattan   b      2999     2975     2975     

我想根据列名转换数据,方法是在“。”处按年和月拆分。

所以数据看起来像这样:

loc        type  year   month  value
Manhattan   a    2010    01     2300
Manhattan   a    2010    02     2300
Manhattan   a    2010    03     2500
Manhattan   b    2010    01     2999
Manhattan   b    2010    02     2975
Manhattan   b    2010    03     2975

我该怎么办?

我正在考虑使用 melt,类似这样的东西,但我对 R 很陌生,知道这是不正确的:

df <- melt(df,id=1,measure=patterns(".",value.name="Value"))

【问题讨论】:

    标签: r dataframe transform data-cleaning reshape2


    【解决方案1】:

    您可以通过pivot_longertidyr 中的separate 实现此目的。试试这个:

    library(dplyr)
    library(tidyr)
    
    df <- read.table(text = "loc      type  2010.01  2010.02  2010.03 
      Manhattan   a      2300     2300     2500     
      Manhattan   b      2999     2975     2975     ", header = TRUE)
    df
    #>         loc type X2010.01 X2010.02 X2010.03
    #> 1 Manhattan    a     2300     2300     2500
    #> 2 Manhattan    b     2999     2975     2975
    
    df %>% 
      pivot_longer(-c(loc:type)) %>% 
      separate(name, into = c("year", "month")) %>% 
      mutate(year = gsub("X", "", year))
    #> # A tibble: 6 x 5
    #>   loc       type  year  month value
    #>   <fct>     <fct> <chr> <chr> <int>
    #> 1 Manhattan a     2010  01     2300
    #> 2 Manhattan a     2010  02     2300
    #> 3 Manhattan a     2010  03     2500
    #> 4 Manhattan b     2010  01     2999
    #> 5 Manhattan b     2010  02     2975
    #> 6 Manhattan b     2010  03     2975
    

    reprex package (v0.3.0) 于 2020-04-04 创建

    【讨论】:

    • 哇,太棒了!据我了解,分开()如何知道该值是年份和月份?我很惊讶指定分隔符“。”不需要
    • 因为这就是我告诉separate 通过into = c("year", "month").(;separate 默认情况下检查标准分隔符,如“.”、“_”、... 来拆分字符串。
    • 我的荣幸。如果你想帮我一个忙:将问题标记为已回答。除了给我一些荣誉之外,它还向其他有类似问题的人表明该解决方案有效,并将该问题从仍在等待答案的问题队列中删除。
    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多