首页 文章

从列中获取一些值以使多个新列与R中的id列匹配

提问于
浏览
2

我在R中有两个数据框:

DF1

Site_code  Species_code  Abundance
    1           MRN          50
    1           TFP          100
    2           MRN          5
    2           XNP          20
    2           AMP          15

在df2中,我有一堆信息,以及站点代码,但每个站点只有一行 . 其他列不感兴趣 .

Site_code   latitude   mean_temp ...etc
    1               55          15
    2               56          10

我想根据df1中的信息为df2中的每个站点创建一个新的数据帧(或矩阵),每个物种有一列,列名与物种代码相同,以及有关的信息 . 列中每个物种的丰度,如果没有在该站点记录物种,则为0值,因此我会得到如下的df:

Site_code   AMP  MRN    TFP   XNP
    1           0     50     100  0  
    2           15    5      0    20

我也想多次这样做,因为我有很多df2,我想为每个df2组成一个新的数据帧 .

我已经阅读了很多关于SO的问题,并且没有遇到过这样的问题 . 如果它已被回答,我真的很感激被指向正确的方向 .

2 回答

  • 1

    您可以使用 reshape2 中的 dcast 函数:

    library(reshape2)
    df2 <- dcast(df1, Site_code ~ Species_code, fill = 0)
    
    df2
    # Site_code AMP MRN TFP XNP
    #         1   0  50 100   0
    #         2  15   5   0  20
    

    简短而简单 .

    您也可以使用 stats 包中的 reshape ,它不需要外部库 .

    # Transpose the data frame by site
    df2 <- reshape(df1,
                   idvar = "Site_code",
                   timevar = "Species_code",
                   direction = "wide")
    
    # Reset NA values to 0
    df2[is.na(df2)] <- 0
    
    # Remove "Abundance." from the column names
    colnames(df2) <- gsub("Abundance.", "", colnames(df2))
    
    df2
    # Site_code MRN TFP XNP AMP
    #         1  50 100   0   0
    #         2   5   0  20  15
    

    reshape 函数使用 NA 填充原始未转置数据集中不存在的值,因此必须手动将这些值重置为0 .

    它还将转置变量的名称附加到新列名称,但可以使用 gsub 删除它 .

  • 3

    R具有多种功能,用于将数据从长格式转换为宽格式,包括预先安装的 stats 包中的 reshapereshape2 包中的 dcast . 在我看来,来自 tidyr 包的 spread 具有最直观的语法:

    library(tidyr)
    spread(df1, Species_code, Abundance, fill = 0)
    

    data

    df1 <- read.table(text = 
    "Site_code  Species_code  Abundance
        1           MRN          50
        1           TFP          100
        2           MRN          5
        2           XNP          20
        2           AMP          15",
    header = TRUE)
    

相关问题