【问题标题】:Transform structure of data frame in RR中数据框的变换结构
【发布时间】:2014-10-09 05:18:50
【问题描述】:

我有一个包含以下列的数据框:

**Columns   Country   Year   Number_of_deaths**
**Data**      US      2000    25
              US      2001    30
              UK      2000    30
              UK      2001    21

我想把它转换成以下格式:

**Columns: Country   2000   2001   2002   2003   2004**
**Data**     US        25     30     35     40     25
             UK        30     21     21     23     45

有人可以给我 R 中的示例代码吗?任何包裹都可以。您的帮助将不胜感激。

【问题讨论】:

  • 使用 reshape2 包中的 dcast
  • @Kabir 谢谢!能否提供一些示例代码?
  • @Moon_Watcher,您的长格式数据似乎与宽格式数据不同。
  • @KFB 假设它是。我没有全部打出来。

标签: r dplyr


【解决方案1】:

按要求制作小图:

library(tidyr)
# creating sample data
dt = data.frame(country = rep(LETTERS[1:2], each=2),
                year = 2000:2003,
                num = c(25,30,30,21))
dt %>% spread(year, num)
#   country 2000 2001 2002 2003
# 1       A   25   30   NA   NA
# 2       B   NA   NA   30   21

【讨论】:

  • @hadley,对。已修改。
【解决方案2】:

使用这个:

希望它有效

library(reshape2)
dcast(data,country~year,value.var="No_of_deaths")

输出:

  country 2000 2001
1      UK   30   21
2      US   25   30

谢谢

【讨论】:

    【解决方案3】:

    这是使用base R的一种方式

     res <- reshape(df, timevar="Year", idvar="Country", direction="wide")
     colnames(res) <- gsub(".*\\.", "",colnames(res)) #if you need `colnames` as `year` alone.  But, it is not good to have `numeric` column names.
    
    
      res
      # Country  2000 2001
      #1      US   25   30
      #3      UK   30   21
    

    如果您使用的是$,请确保使用backticks

      res$`2000`
      #[1] 25 30
    

    数据

      df <- structure(list(Country = c("US", "US", "UK", "UK"), Year = c(2000L, 
      2001L, 2000L, 2001L), Number_of_deaths = c(25L, 30L, 30L, 21L
      )), .Names = c("Country", "Year", "Number_of_deaths"), class = "data.frame", row.names = c(NA, 
     -4L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多