如何修复“二进制运算符的非数字参数”

时间:2019-07-15 07:21:58

标签: r

我想制作一个瀑布图,实际上我已经成功地获得了一个好图。然后,我想使用ifelse函数添加一个二进制列。现在,该功能不起作用,并显示“非数字参数...”。谁能帮我?谢谢!

library(tumgr) 
library(ggplot2)
library(tidyverse)
set.seed(1234)
tumorgrowth = sampleData
tumorgrowth = do.call(rbind,
by(tumorgrowth, tumorgrowth$name,
     function(subset) within(subset,
              { treatment = ifelse(rbinom(1,1,0.5), "Drug","Control")   
#random classfied
                o = order(date)
                date = date[o]
                size = size[o]
                baseline = size[1]
                percentChange = 100*(size-baseline)/baseline
                time = ifelse(date > 250, 250, date)                    
                cstatus = factor(ifelse(date > 250, 0, 1))
              })))
 tumorgrowth1 = tumorgrowth%>%
   group_by(name)%>%
   mutate(patient=percentChange[which.max(abs(percentChange))])%>%
   select(name,patient,cstatus)
o=order(tumorgrowth1$patient,decreasing = TRUE)
tumorgrowth1=tumorgrowth1[o,]
tumorgrowth1=distinct(tumorgrowth1)

col=ifelse(tumorgrowth1$cstatus==0, "#BC5A42", "#009296")

# This function does not work after adding the "col" column
waterfall=function(data,var){
  barplot(data[,var],width=0.1,col=col, border=col,cex.axis=1.2, 
  cex.lab=1.4)
}
waterfall(tumorgrowth1,"patient")

1 个答案:

答案 0 :(得分:0)

你很近。对于barplot,您需要转置矩阵,可以使用t()实现。由于cstatus是一个因子列,因此此步骤会将所有数据转换为"character"。可能不需要该列,因此我们可以通过简单地排除它来解决此问题。自然地,在您的函数中,您必须将var移动到行中。

waterfall <- function(data,var) {
  barplot(data[var, ], width=0.1, col=col, border=col, cex.axis=1.2, 
          cex.lab=1.4)
}
waterfall(t(tumorgrowth1[-3]), "patient")

enter image description here