r - Manipulating dataframe without for loop -
i wrote loop manipulate rather large (~1,000,000 rows) dataframe runs far slow , couldn't find online.
df=data.frame(v1=runif(10), v2=runif(10), v3=runif(10), v4=0, v5=0, v6=0, v7=0) for( in 1:dim(df)[1] ) { df[i,4]=length(which(df[i,1:3]>0.00 & df[i,1:3]<0.10)) df[i,5]=length(which(df[i,1:3]>0.10 & df[i,1:3]<0.50)) df[i,6]=length(which(df[i,1:3]>0.50 & df[i,1:3]<0.90)) df[i,7]=length(which(df[i,1:3]>0.90 & df[i,1:3]<1.00)) }
i've tried write function this, adds row together:
test.fun <- function (df) { df[,4]=length(which(df[,1:3]>0.00 & df[,1:3]<0.10)) df[,5]=length(which(df[,1:3]>0.10 & df[,1:3]<0.50)) df[,6]=length(which(df[,1:3]>0.50 & df[,1:3]<0.90)) df[,7]=length(which(df[,1:3]>0.90 & df[,1:3]<1.00)) return(df) } (test <- test.fun(df))
rowsums
condition want main idea.
you can use dplyr
package make cleaner:
df %>% mutate(v4 = rowsums(df[,1:3]>0.00 & df[,1:3]<0.10))%>% mutate(v5 = rowsums(df[,1:3]>0.10 & df[,1:3]<0.50))%>% mutate(v6 = rowsums(df[,1:3]>0.50 & df[,1:3]<0.90))%>% mutate(v7 = rowsums(df[,1:3]>0.90 & df[,1:3]<1.00)) # v1 v2 v3 v4 v5 v6 v7 # 1 0.2875775 0.95683335 0.8895393 0 1 1 1 # 2 0.7883051 0.45333416 0.6928034 0 1 2 0 # 3 0.4089769 0.67757064 0.6405068 0 1 2 0 # 4 0.8830174 0.57263340 0.9942698 0 0 2 1 # 5 0.9404673 0.10292468 0.6557058 0 1 1 1 # 6 0.0455565 0.89982497 0.7085305 1 0 2 0 # 7 0.5281055 0.24608773 0.5440660 0 1 2 0 # 8 0.8924190 0.04205953 0.5941420 1 0 2 0 # 9 0.5514350 0.32792072 0.2891597 0 2 1 0 # 10 0.4566147 0.95450365 0.1471136 0 2 0 1
data:
set.seed(123) #to make reproducible example df=data.frame(v1=runif(10), v2=runif(10), v3=runif(10), v4=0, v5=0, v6=0, v7=0)
Comments
Post a Comment