Wil - 7 months ago 27

R Question

I am using ggplot to plot a dataset.

The dataset is like this:

`pr0 pr1`

A1 0.1 0.9

A2 0.2 0.8

A3 0.7 0.3

Below is my code:

`aggregate <- function(){agg.1 <- data`

rownames(agg.1) <- colnames(Q)

agg <- melt(agg.1)

per.agg <- paste(round(100*(agg.1[,2]), 2), "%", sep="")

text <- paste(per.agg[1],"have A1","\n",

per.agg[2],"have A2","\n",

per.agg[3],"have A3","\n")

ggplot(data=agg,aes(x=agg[,1], y=agg[,3],fill=factor(agg[,2])))+

geom_bar(stat="identity",position = "stack")+

xlab("")+ylab("Aggregated Examinee Attribute Mastery Rate")+

ggtitle(text)

}

The problem is that the possible numbers in per.agg[_] may range from 1 to 100, and in "of examinees have mastered A1", "A1" could be from 1 to 100. Now I have listed three, but when I have four, for example,

`pr0 pr1`

A1 0.1 0.9

A2 0.2 0.8

A3 0.7 0.3

A4 0.3 0.7

I will need to add per.agg[4], and A4. The number will be the same as ncol(Q). How can I incorporate every possible number?

Answer

Here's an example which I think you could pretty quickly adapt to your situation:

```
set.seed(123)
df1 <- data.frame(x = letters[1:5],
y = rpois(5,5))
df1
# x y
# 1 a 4
# 2 b 7
# 3 c 4
# 4 d 8
# 5 e 9
```

`sapply`

, `paste`

, and specify `collapse = ' \n '`

```
paste(sapply(1:nrow(df1),
function(x) paste(df1[x,2], 'have', paste0('A',x))),
collapse = ' \n ')
# "4 have A1 \n 7 have A2 \n 4 have A3 \n 8 have A4 \n 9 have A5"
```

For your example, I think you'd replace `1:nrow(df1)`

with `1:ncol(Q)`

and `df1[x,2]`

with `per.agg[x]`

:

```
paste(sapply(1:ncol(Q),
function(x) paste(per.agg[x], 'have', paste0('A',x))),
collapse = ' \n ')
```