user6529266 - 2 years ago 59

R Question

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

`mat`

`MatA, MatB, MatC`

`df`

`MatA, MatB, MatC`

`df`

I tried using loops, apply functions but am lost at how to use the column values

`MatA`

`df$mat`

`MatA`

`sum(MatA==1)`

`df`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**