Hi all,
Thanks for the suggestions. I have not yet tried the apply ()
approach, but have tried to get the indexed version working, so far
with limited success. I realize that a transpose, as suggested,
would work, but want to avoid that for something simpler.
To repeat, the task is to perform a function on N rows (all numeric)
in a data frame. I can use rowMeans, rowSums, pmin, and pmax to
successfully average, sum, and find the min/max var1-var4). But If I
try to get the mean (var5) using, no doubt the incorrect syntax:
mean(df[,c(4,5,6,7)], na.rm=T), I do not get the mean of 4 column. I
am not sure what is being returned as a value.
I summarize the code below with the output: any further suggestions
are appreciated,
Thanks Gerard
Code with output:
> df <- read.table(textConnection("id,workshop,gender,q1,q2,q3,q4
+ 1,1,f,1,1,5,1
+ 2,2,f,2,1,4,1
+ 3,1,f,2,2,4,3
+ 4,2,f,3,1, ,3
+ 5,1,m,4,5,2,4
+ 6,2,m,5,4,5,5
+ 7,1,m,5,3,4,4
+ 8,2,m,4,5,5,5"), header=TRUE, sep=",")
>
> attach(df)
>
> df$var1<-rowMeans(cbind(q1,q2,q3,q4),na.rm=T)
> df$var2<-rowSums (cbind(q1,q2,q3,q4),na.rm=T)
> df$var3<-pmin(q1,q2,q3,q4, na.rm=T)
> df$var4<-pmax(q1,q2,q3,q4, na.rm=T)
>
> df$var5<-mean(df[,c(4,5,6,7)],na.rm=T) #not doing what I want
> df$var6<-sd (df[,c(4,5,6,5)],na.rm=T) #not doing what I want
> df$var7<-min (df[,c(4,5,6,5)],na.rm=T) #not doing what I want
> df$var8<-max (df[,c(4,5,6,5)],na.rm=T) #not doing what I want
>
> df
output with problem vars underlined:
id workshop gender q1 q2 q3 q4 var1 var2 var3
var4 var5 var6 var7 var8
1 1 1 f 1 1 5 1 2.000000 8 1 5 3.250000
1.488048 1 5
2 2 2 f 2 1 4 1 2.000000 8 1 4 2.750000
1.752549 1 5
3 3 1 f 2 2 4 3 2.750000 11 2 4 4.142857
1.069045 1 5
4 4 2 f 3 1 NA 3 2.333333 7 1 3 3.250000
1.752549 1 5
5 5 1 m 4 5 2 4 3.750000 15 2 5 3.250000
1.488048 1 5
6 6 2 m 5 4 5 5 4.750000 19 4 5 2.750000
1.752549 1 5
7 7 1 m 5 3 4 4 4.000000 16 3 5 4.142857
1.069045 1 5
8 8 2 m 4 5 5 5 4.750000 19 4 5 3.250000
1.752549 1 5
>
[[alternative HTML version deleted]]
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.