数据帧列表中每个数据帧的多个图的功能

时间:2017-11-25 23:46:04

标签: r ggplot2

我的程序传递了几个具有任意名称的数据框的mylist列表:

FOO  12     tbl_df list
BAR  12     tbl_df list
...

每个数据帧都具有相同的结构:

variableX    variableY    SUBJECT_ID     SUBJECT_YEAR          SUBJECT_TOWN
2            1            A              1950                  Townsville
1            2            B              1951                  Villestown
...

我需要迭代mylist,为每个数据帧获取一个平均variableXSUBJECT_YEARSUBJECT_TOWN的图,以便将其导出为唯一命名的图像文件(例如FOO_SUBJECTOWN.png)。

我知道R可以很好地处理这类任务,并且在使用for循环执行此任务时有很好的例子。但是,因为我不熟悉R中的函数,所以我想知道如何使用函数有效地执行此任务。

1 个答案:

答案 0 :(得分:0)

这应该有效

#cast them to characters before proceeding, ok? 
unique.years = unique(dataframe$SUBJECT_YEAR)
unique.town = unique(dataframe$SUBJECT_TOWN)

mean.years = c()
mean.town = c()

for(i in 1:length(unique.years))
{
    mean.years [i] = mean( dataframe[ dataframe[,"SUBJECT_YEAR"] == unique.years[i]  ,"variableX" ] )
}


for(i in 1:length(unique.town))
{
    mean.town [i] = mean( dataframe[ dataframe[,"SUBJECT_TOWN"] == unique.years[i]  ,"variableX" ] )
}

jpeg('years.jpg')
plot(x = unique.years, y = mean.years)
dev.off()

jpeg('town.jpg')
plot(x = unique.town, y = mean.town)
dev.off()

您可以稍后为您想要的任何唯一更改唯一变量。此外,在情节中添加标题和图例,也许是一些颜色,会很好。

如果它是数据帧列表,只需在循环中替换myList [[j]]的数据帧,如下所示

for(j in 1:length(myList))
}
    #cast them to characters before proceeding, ok? 
    unique.years = unique(myList[[j]]$SUBJECT_YEAR)
    unique.town = unique(mylist[[j]]$SUBJECT_TOWN)

    mean.years = c()
    mean.town = c()

    for(i in 1:length(unique.years))
    {
        mean.years [i] = mean( myList[[j]] [ myList[[j]][,"SUBJECT_YEAR"] == unique.years[i]  ,"variableX" ] )
    }


    for(i in 1:length(unique.town))
    {
        mean.town [i] = mean( myList[[j]][ myList[[j]][,"SUBJECT_TOWN"] == unique.years[i]  ,"variableX" ] )
    }

    jpeg(paste0("years",j,".jpg")
    plot(x = unique.years, y = mean.years)
    dev.off()

    jpeg(paste0("town",j,".jpg")
    plot(x = unique.town, y = mean.town)
    dev.off()
}