【问题标题】:R: Barplots & Separating them by variablesR:条形图并按变量分隔它们
【发布时间】:2015-11-26 22:23:05
【问题描述】:

我得到了一个数据集,并将其转换为矩阵。我一直想知道如何根据列中矩阵的值创建条形图。我基本上必须比较 2 个变量,它们是手术的年份及其生存状态。他们的生存状态基于 2 个值,1 是他们活了 5 年以上,2 是他们在 5 年内死亡。我想将两者与另一个变量进行比较,具体取决于它们是否在 1965 年之前和 1965 年之后进行过手术。所以我总共要寻找 4 个酒吧,其中 1 个是在 1965 年之前进行过手术并幸存下来,另一个是他们在 1965 年之前进行了手术并死亡,另一种是在 1965 年之后进行了手术并幸存下来,另一种是在 1965 年之后进行了手术并死亡。如果有人可以帮助我,我将不胜感激!我的代码如下:

data<-data.matrix(readingfile)
Survival<-c(data[,4])
Year<-c(data[,2])
Comparison<-matrix(c(Year,Survival),ncol=2)
barplot(Comparison) # I know it's this line of code I will have to add arguments in, in order to make it work.

【问题讨论】:

    标签: r


    【解决方案1】:

    我不确定我是否理解您的问题。因此,我为您提供了一个非常基本的解决方案,并且我将所有阶段分开,因此一定有一些对您有用的地方;-)

    告诉我进展如何!

    # Let's first create some fake data
    survival <- sample(1:2, 100, replace=T)
    year <- sample(1940:1990, 100, replace=T)
    comparison <- data.frame(year, survival)
    
    # We sum each category for each year
    sum.per.year <- rbind(tapply(comparison$survival, comparison$year, function(x) sum(x==1)),
        tapply(comparison$survival, comparison$year, function(x) sum(x==2)))
    # We create a logical vector to check what years are in the period we target
    year.before.1965 <- sapply(colnames(sum.per.year), function(c) as.numeric(c)<1965)
    # Now we aggregate (sum) the results for before and after 1965
    sum.per.year <- t(data.matrix(sum.per.year))
    res <- sapply(1:2,function(c) tapply(sum.per.year[,c],year.before.1965,sum))
    colnames(res) <- c("Lived.over.5","Died.in.5")
    rownames(res) <- c("Before.1965","After.1965")
    
    # And finally we output
    barplot(res, beside=T, col=c("blue","red"))
    legend("topleft", rownames(res), pch=15, col=c("blue","red"), bty="o")
    
    # OR, depending on what how you want to present the results
    barplot(t(res), beside=T, col=c("blue","red"))
    legend("topleft", colnames(res), pch=15, col=c("blue","red"), bty="o")
    

    【讨论】:

    • 这正是我所需要的,非常感谢!结果并不完全符合我的预期,但这对我有很大帮助!再次感谢您! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多