0

I have a dataframe df that looks like this

        a    b     c     d
row1    1    2     2     3
row2    2    4     5     9
row3    1    4     4     6

For each row I want to write a histogram to a page in a pdf. I tried to do it like this

for (i in 1:nrow(df)){
    histogram <- ggplot(data=df, aes(x=as.numeric(df[i,]))) +geom_histogram()
    ggsave(filename="output.pdf", plot=histogram)
}

However, this gives me the error arguments imply differing number of rows: 115, 734. From this answer: https://stackoverflow.com/a/26148043/651779 I tried to do

df$id <- rownames(df)
df <- melt(df)
for (i in 1:nrow(df)){
  histogram <- ggplot(data=df, aes(x=as.numeric(df[i,]))) +geom_histogram()
  ggsave(filename="output.pdf", plot=histogram)
}

but this gives me the same error but with a different number arguments imply differing number of rows: 3, 84410

Community
  • 1
  • 1
Niek de Klein
  • 8,524
  • 20
  • 72
  • 143

2 Answers2

2

How about:

for (i in 1:nrow(df)) {
  df2 <- data.frame(x = as.numeric(df[i, ]))
  histogram <- ggplot(data = df2, aes(x)) + geom_histogram()
  ggsave(filename = "output.pdf", plot = histogram)
}
Axeman
  • 32,068
  • 8
  • 81
  • 94
2

I would transpose the data.frame using t and then plot like this:

#transpose df
df <- data.frame(t(df))

#notice aes_string in order for i to be the name as character
for (i in names(df)){
  histogram <- ggplot(df, aes_string(x=i)) + geom_histogram()
  ggsave(filename="output.pdf", plot=histogram)
}
LyzandeR
  • 37,047
  • 12
  • 77
  • 87