【问题标题】:Getting dataframe colum names with apply for graph title in R使用 R 中的图形标题获取数据框列名称
【发布时间】:2019-03-07 18:11:41
【问题描述】:

我在数据框的列上运行应用函数并执行多项操作,包括绘制一些图表。我想获取列名以将它们用作每个图的标题。我找到了post that uses lapply,但我认为我不能使用它,因为我需要申请。

var1<-rnorm(100)
var2<-rnorm(100)
var3<-rnorm(100)  
df<-data.frame(var1,var2, var3)  
colnames(df)<-c("var1", "var2", "var3")  

myFUN<-function(x){  

  themean<-mean(x)  
  thevar<-var(x)  

  Name<-colnames(x)  
  thetitle <- paste('Variable: ', Name, '')  
  hist(x,main=thetitle)  

return(list(themean, thevar))  
}  

apply(df,2,myFUN)  

【问题讨论】:

  • 为什么需要apply?您的apply 调用等效于lapply(df, myFUN)

标签: r dataframe graph apply columnname


【解决方案1】:

您可以使用mapply,这是sapply 的多变量版本。但是你需要重写函数来接受两个参数。

myFUN2 <- function(x, Name){ 

  themean <- mean(x)  
  thevar <- var(x)  

  thetitle <- paste('Variable: ', Name, '')  
  hist(x, main = thetitle)  

  return(list(themean, thevar))  
}  

mapply(myFUN2, df, names(df))
mapply(myFUN2, df, names(df), SIMPLIFY = FALSE)

第一次调用将输出简化为矩阵。第二个没有,它返回一个列表。

【讨论】:

    【解决方案2】:

    我会使用lappy,例如:

    myFUN<-function(x){  
    
      themean<-mean(df[[x]])  
      thevar<-var(df[[x]])  
    
      Name<-x  
      thetitle <- paste('Variable: ', Name, '')  
      hist(df[[x]],main=thetitle, xlab = Name)  
    
      return(list(themean, thevar))  
    }  
    
    lapply(names(df), myFUN)  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2022-01-26
      • 1970-01-01
      • 2015-09-26
      • 2020-12-02
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多