Add variables whilst ignoring NA`s using transform function

后端 未结 2 589
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 05:14

I have a data frame with a large number of variables. I am creating new variables by adding together some of the old ones. The code I am using to do so is:

n         


        
2条回答
  •  渐次进展
    2021-01-03 05:49

    Using rowSums and prod could help you out.

    set.seed(007) # Generating some data
    DF <- data.frame(V1=sample(c(50,NA,36,24,80, NA), 15, replace=TRUE),
                     V2=sample(c(70,40,NA,25,100, NA), 15, replace=TRUE),
                     V3=sample(c(20,26,34,15,78,40), 15, replace=TRUE))
    
    transform(DF, Sum=rowSums(DF, na.rm=TRUE)) # Sum (a vector of values)
    transform(DF, Prod=apply(DF, 1, FUN=prod, na.rm=TRUE)) # Prod (a vector of values)
    
    # Defining a function for substracting (resta, in spanish :D)
    resta <- function(x) Reduce(function(a,b) a-b,  x <- x[!is.na(x)])
    transform(DF, Substracting=apply(DF, 1, resta))
    
    # Defining a function for dividing 
    div <- function(x) Reduce(function(a,b) a/b,  x <- x[!is.na(x)])
    transform(DF, Divsion=apply(DF, 1, div))
    

提交回复
热议问题