简体   繁体   中英

sum, roundoff and replace values in R


I have two questions?

 > data<-read.table("UC.txt",header=TRUE, sep="\t")
 > data$tot<-data$P1+data$P2+data$P3+data$P4
 > head(data, 5)
      geno    P1    P2    P3    P4   tot
    1   G1 0.015 0.007 0.026 0.951 0.999
    2   G2 0.008 0.006 0.015 0.970 0.999
    3   G3 0.009 0.006 0.017 0.968 1.000
    4   G4 0.011 0.007 0.017 0.965 1.000
    5   G5 0.013 0.005 0.021 0.961 1.000

Question #1: sometimes, number of column varies, so, how to sum column2 to last column. something like data[2]:data[n]

library("plyr")
> VD<-function(P4, tot){
   if(tot > 1) {return(P4-0.01)}
   if(tot < 1) {return(P4+0.01)}
   if(tot == 1) {return(P4)}
 }
> minu<-ddply(data, 'geno', summarize, Result=VD(P4, tot))
> v <- data$geno==minu$geno
> data[v, "P4"] <- minu[v, "Result"]
> data <- subset(data, select = -tot)
> data$tot<-data$P1+data$P2+data$P3+data$P4
> head(data, 5)
  geno   P1   P2   P3   P4 tot
1   G1 0.02 0.01 0.03 0.94   1
2   G2 0.01 0.01 0.02 0.96   1
3   G3 0.01 0.01 0.02 0.96   1
4   G4 0.01 0.01 0.02 0.96   1
5   G5 0.01 0.01 0.02 0.96   1

Question #2: Here, I need to roundoff 'tot' to 1 by adjusting P1 to P4.
condition :
1) I should adjust the maximum among P1 to P4
2) The adjusting values may differ, like 0.01, 0.001, 0.0001. ( it is based on 1-tot)
How to do this?
Thanks in advance

对于问题1,对除第一列以外的所有列求和:

dat$tot <- rowSums(dat[,-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM