I am trying to add a new column to an existing data frame which shows the number of one's in a binary matrix. One column in the existing data frame has the the matrix names whose count/sum I am trying to find.
For example,
r <- 10
c <- 10
MatA <- matrix(sample(0:1,r*c, replace=TRUE),r,c)
MatB <- matrix(sample(0:1,r*c, replace=TRUE),r,c)
MatC <- matrix(sample(0:1,r*c, replace=TRUE),r,c)
mat <- c("MatA","MatB","MatC")
size <- c(4,6,10)
df <- data.frame(mat,size)
mat
MatA, MatB, MatC
df
MatA, MatB, MatC
df
MatA
df$mat
MatA
sum(MatA==1)
df
Use get
to reference variable by string
set.seed(7)
df$binary <- lapply(mat, function(x) sum(get(x)))
To use the data.frame column if stored as factors
df$binary <- lapply(levels(df$mat)[df$mat], function(x) sum(get(x)))
To store column as strings and not factors
df <- data.frame(mat, size, stringsAsFactors = FALSE)
df$binary <- lapply(df$mat, function(x) sum(get(x)))
> df
mat size binary
1 MatA 4 47
2 MatB 6 58
3 MatC 10 54