[R] help with a simple function
arun
smartpink111 at yahoo.com
Fri Sep 13 07:12:43 CEST 2013
Hi,
rownames(y_raw_mt)=y_raw[,1] ## y_raw not defined.
set.seed(25)
mat1<- matrix(sample(c(NA,1:20),100,replace=TRUE),20,5)
#changed the function to process 'mat1'. Also, it is better to read the file separately and check ?str(dt.table) before proceeding.
write.table1=function(durty_data){
# dt.table=read.table(durty_data, sep = "\t", header=T)#
# y_raw_mt=as.matrix(dt.table[2:174])####
y_raw_mt<- durty_data
rownames(y_raw_mt)= paste0("Col",1:nrow(y_raw_mt)) #assigning the raw names to the matrix
y_raw_mt_t=t(y_raw_mt)####
y_raw_mt_t_mean=apply(y_raw_mt_t, 2, mean, na.rm=T)###
means=c(y_raw_mt_t_mean)##
y_raw_mt_t_meanbind=rbind(y_raw_mt_t,means)##
t=function(x) {
x[is.na(x)] = mean(x, na.rm = T)
return(x)
}
write.a.nice.table=apply(y_raw_mt_t_meanbind,2,t)
return(write.a.nice.table)
}
#Function seemed to work as intended.
write.table1(mat1)
Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 Col10 Col11 Col12 Col13
8 14.0 3.0 18.0 2.0 20 13.0 7.0 1.0 5 6.0 7 20.0
9 9.0 1.0 3.0 6.0 6 1.0 12.0 11.0 4 17.0 7 4.0
14 5.0 11.0 15.0 11.0 6 20.0 14.0 1.0 15 2.0 15 17.0
2 4.0 6.0 14.0 13.0 17 9.0 18.0 13.0 5 18.0 2 1.0
12 7.0 10.0 1.0 16.0 16 6.0 8.0 16.0 11 10.0 4 12.0
means 9 7.8 6.2 10.2 9.6 13 9.8 11.8 8.4 8 10.6 7 10.8
Col14 Col15 Col16 Col17 Col18 Col19 Col20
12.0 14.0 3 11.0 15.0 10.0 15
2.0 17.0 8 19.0 7.0 3.0 2
10.0 11.0 2 2.0 11.0 3.0 2
16.0 4.0 9 2.0 17.0 3.0 3
13.0 11.5 8 13.0 18.0 4.0 3
means 10.6 11.5 6 9.4 13.6 4.6 5
rowMeans(mat1,na.rm=TRUE)
# [1] 9.0 7.8 6.2 10.2 9.6 13.0 9.8 11.8 8.4 8.0 10.6 7.0 10.8 10.6 11.5
#[16] 6.0 9.4 13.6 4.6 5.0
A.K.
hi, I am new to are, very new and want to ask what's wrong with this
function: It is suppose to read a table and return its matrix transposed
with NA replaced by the average of each column and a row of means at
the bottom row. The separated parts are returned correctly. Thanks a lot
for any help.
Guy
write.table=function(durty_data){
dt.table=read.table(durty_data, sep = "\t", header=T)#
y_raw_mt=as.matrix(dt.table[2:174])####
rownames(y_raw_mt)=y_raw[,1] #assigning the raw names to the matrix
y_raw_mt_t=t(y_raw_mt)####
y_raw_mt_t_mean=apply(y_raw_mt_t, 2, mean, na.rm=T)###
means=c(y_raw_mt_t_mean)##
y_raw_mt_t_meanbind=rbind(y_raw_mt_t,means)##
t=function(x) {
x[is.na(x)] = mean(x, na.rm = T)
return(x)
}
write.a.nice.table=apply(y_raw_mt_t_meanbind,2,t)
return(write.a.nice.table)
}
More information about the R-help
mailing list