在lapply函数中打印列名 [英] Printing a column name inside lapply function

查看:62
本文介绍了在lapply函数中打印列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了所有档案,但没有找到合适的答案.我是一个初学者,如果我提出一个非常基础的查询,请原谅我的无知.我正在尝试获取apply函数以在通过数据框进行处理时打印列名称.我知道lapply将数据帧的列转换为向量,但是这是他们在打印输出时打印列名称的方式.就像下面的例子一样

I have searched through the archives but have not found a suitable answer. I am a beginner and please excuse my ignorance if I am posing a very elementary query. I am trying to get the apply function to print the column names while processing through a data frame. I understand that lapply converts the column of data frame to vector, but is their way to print the column name while printing output. Like in the following example

   > mydata<-data.frame(matrix(rep(c(1:2),times= 50),20,5))
   > colnames(mydata)<-letters[1:5]
   > lapply(mydata[,2:4],function(x){CrossTable(x,mydata[,5])})

我希望输出在打印输出表时显示正在处理的列名.现在,它们仅在列联表中仅打印"x".

I want the output to show the column name it is processing while printing the output table. It only prints only "x" right now in the contingency tables.

推荐答案

好的,这很老了,但是我遇到了同样的问题,并且希望分享我的方法,尽管它在某种程度上违反了* apply想法.好处是:您可以在循环中集成任何内容.因此,我需要对2个输出变量运行方差分析,具体取决于我通过lapply遍历的列,获取p_value来注释绘图并并排创建多个绘图. 核心是它结合了for循环和lapply

Ok, this is old, but I came across the same problem and wanted to share my approach, although it violates to some extent the *apply idea. The upside is: you can integrate anything in the loop. So I needed to run an ANOVA on 2 output variables, depending on columns I looped through with lapply, get the p_values to annotate the plot and create multiple plots side-by-side. The core is that it combines a for-loop with lapply

for (i in 0:10){
i<-i+1
lapply(df[i],function(x) {
  myfactor<-names(df)[i] #gets the column name
  anova_model_a<-lm(a~x,df) #needed to run ANOVA per column
  anova_model_b<-lm(b~x,df) #needed to run ANOVA per column
  tab_aov_a<-tidy(summary(anova_model_a)) #proper result table
  tab_aov_b<-tidy(summary(anova_model_b)) #proper result table
  labels_a <- data.frame(drv = "1", label=c(round(tab_aov_a$p.value[2],4))) #needed for labelling the graph. I only had 2 groups for comparison
  labels_b <- data.frame(drv = "1", label=c(round(tab_aov_b$p.value[2],4))) #needed for labelling the graph
  fig1<-ggplot(df,aes(x,a))+
    geom_boxplot()+
    ggtitle("a")+
    geom_text(data=labels_a,aes(x=drv,y=12,label=label),colour="blue",angle=0,hjust=0.5, vjust=0.5,size=5)+
    xlab(myfactor)

  fig2<-ggplot(df,aes(x,b))+
    geom_boxplot()+
    ggtitle("b")+
    geom_text(data=labels_b,aes(x=drv,y=6,label=label),colour="blue",angle=0,hjust=0.5, vjust=0.5,size=5)+
    xlab(myfactor)
  arrangement<-grid.arrange(fig1,fig2,nrow=2)
  print(arrangement)
})
}

这篇关于在lapply函数中打印列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆