user6529266 user6529266 - 2 years ago 67
R Question

R - Using column value in data frame to lookup matrix name and summarize matrix

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)

I need to lookup the
column values such as
MatA, MatB, MatC
dataframe to match the matrix names
MatA, MatB, MatC
and return the number of 1's in each of the binary matrix added to the
dataframe in a new column.

I tried using loops, apply functions but am lost at how to use the column values
as a lookup for matrix name
and return
to new column in dataframe

Answer Source

Use get to reference variable by string

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download