I have a number of dataframes (96) that have columns of 0s and 1s. If there is more than one "1" in any one column of the dataframes, I want to replace the 1s with a equal fractions so that the sum of the values in the column is 1, as shown in the code below.
v1 <- c(0, 1, 0, 1, 1, 0)
v2 <- c(0, 0, 1, 0, 0, 0)
v3 <- c(0, 0, 1, 1, 0, 0)
df1 <- data.frame(v1, v2, v3)
df2 <-data.frame(v3, v3, v1)
df3 <- data.frame(v1, v3, v1)
new.df1 <- t(apply(df1, 2, FUN = function(x) {
if(sum(x==1, na.rm=TRUE) ==2) replace(x, x==1, 0.5)
else if (sum(x==1, na.rm=TRUE)==3) replace( x, x==1, 1/3)
else x}))
new.df2 <- t(apply(df2, 2, FUN = function(x) {
if(sum(x==1, na.rm=TRUE) ==2) replace(x, x==1, 0.5)
else if (sum(x==1, na.rm=TRUE)==3) replace( x, x==1, 1/3)
else x}))
new.df3 <- t(apply(df3, 2, FUN = function(x) {
if(sum(x==1, na.rm=TRUE) ==2) replace(x, x==1, 0.5)
else if (sum(x==1, na.rm=TRUE)==3) replace( x, x==1, 1/3)
else x}))
I am able to create what I want with brute force as in the above example, but there must be a better (more concise) way. I'd greatly appreciate some help.