[R] Question
arun
smartpink111 at yahoo.com
Thu Jul 31 07:19:44 CEST 2014
Hi Farnoosh,
Regarding the first question:
dat2 <- dat1
dat1$Mean <- setNames(unsplit(sapply(split(dat1[,-1], dat1[,1]),rowMeans, na.rm=T),dat1[,1]),NULL)
dat1
Unit q1 q2 q3 Mean
1 A 3 1 2 2.000000
2 A 2 NA 1 1.500000
3 B 2 2 4 2.666667
4 B NA 2 5 3.500000
5 C 3 2 NA 2.500000
6 C 4 1 4 3.000000
7 A 3 2 NA 2.500000
second question, is not clear. Assuming that you want something like this:
dat2[,-1] <- (!is.na(dat2[,-1]))+0
dat2$indx <- with(dat2, ave(rep(1, nrow(dat2)), Unit, FUN=cumsum))
library(reshape2)
dcast(melt(dat2, id.var=c("indx","Unit")), variable+indx~Unit, value.var="value", fill=0)[,-2]
variable A B C
1 q1 1 1 1
2 q1 1 0 1
3 q1 1 0 0
4 q2 1 1 1
5 q2 0 1 1
6 q2 1 0 0
7 q3 1 1 0
8 q3 1 1 1
9 q3 0 0 0
A.K.
On Wednesday, July 30, 2014 1:42 PM, farnoosh sheikhi <farnoosh_81 at yahoo.com> wrote:
Hi Arun,
I have two questions, I have a data like below:
dat1<-read.table(text="
Unit q1q2q3
A312
A2NA1
B224
BNA25
C32NA
C414
A32NA
",sep="",header=T,stringsAsFactors=F)
I want to get the average of each row by the number of answered questions. For example second row would be (2+1)/2 since there is a NA.
Secondly, I want to pivot the units like: UnitA, UnitB, Unit C as columns and have 1 and zero as values.
Thanks a lot for your help.
More information about the R-help
mailing list