[R] Linebreaks in cat() functions that call other variables?

arun smartpink111 at yahoo.com
Wed May 22 23:24:51 CEST 2013


HI,
Try:

lab2<- function(var1,var2,data1){
 a<- anova(lm(var2~var1,data=data1))
cat("df(between) is",a[1,1],"\n")
  cat("df(within) is", a[2,1],"\n")
  cat("ss(between) is", a[1,2],"\n")
  cat("ss(within) is", a[2,2],"\n")
 }

#or
lab3<- function(var1,var2,data1){
 a<- anova(lm(var2~var1,data=data1))
cat(paste(paste("df(between) is",a1[1,1]),paste("df(within) is",a1[2,1]),paste("ss(between) is",a1[1,2]),paste("ss(within) is", a1[2,2]),sep="\n"))
 }

set.seed(28)
 dat1<- data.frame(Val=c(rnorm(10,25),rnorm(10,20),rnorm(10,22.5)),Group=rep(1:3,each=10))
dat1$Group<- factor(dat1$Group)
lab3(dat1$Group,dat1$Val,dat1)
#df(between) is 2
#df(within) is 27
#ss(between) is 109.581925181783
#ss(within) is 27.5035727619943> 

lab2(dat1$Group,dat1$Val,dat1)
#df(between) is 2 
#df(within) is 27 
#ss(between) is 109.5819 
#ss(within) is 27.50357 

A.K.


Hi everyone, 

I'm having some difficulty getting the linebreaks I want with the cat() function. 

I currently have the following function: 

lab1<-function(iv,dv){ 
  a<-anova(lm(dv~iv)) 
  cat("df(between) is",a[1,1]) 
  cat("df(within) is", a[2,1]) 
  cat("ss(between) is", a[1,2]) 
  cat("ss(within) is", a[2,2]) 
} 

And I want my output to be: 

df(between) is 4 
df(within) is 45 
ss(between) is 232 
ss(within) is 400 

but instead it prints: 
df(between) is 4df(within) is 45ss(between) is 232ss(within) is 400 


I have seen other people ask about this issue, but only in 
the context of character strings. I understand that if i wanted the 
output: 

Happy birthday 
to you 

the correct input would be 
>cat("Happy birthday\ntoyou") 

However applying the same logic to my string returns an error: 
> cat("df(between) is",a[1,1],\n"df(within) is", a[2,1]) 
Error: unexpected input in "cat("df(between) is",a[1,1],\" 
> cat("df(between) is",a[1,1]\n"df(within) is", a[2,1]) 
Error: unexpected input in "cat("df(between) is",a[1,1]\" 

Adding the command 'sep="\n"' to the end of each cat() returns: 

df(between) is 
4 
df(within) is 
45 
ss(between) is 
232 
ss(within) is 
400 

which is not quite as ugly, but I would still prefer the 4 line format I posted at the beginning. 

Can anyone help?



More information about the R-help mailing list