简体   繁体   中英

Generating column names to iterate over data frame in R

I'm new to R, so please bear with me... I managed to load a data frame, and the header has columns such "data$xy1" and "data$xy2". I want to programmatically generate the column names to extract each column and plot a histogram. In short, I want to construct 'data$xy' + n, where I'm going to iterate over n. I tried cat and got:

as.name(cat("data$x.y", i, sep="."))
data$x.y.1Error in as.name(cat("data$x.y", i, sep = ".")) : 
invalid type/length (symbol/0) in vector allocation
names(data)

should get your column names

if you want a histogram for each column of data

for(i in names(data)){
  png(paste(i,'.png',sep=""))
  hist(data[,which(names(data)==i)],
       main=paste(i,"some other stuff"),
       xlab=paste(i,"some more stuff") 
      )
  dev.off()
}

That will plant a bunch of .png files with names like xy1.png in your working directory.

df <- data.frame(x = rnorm(5), x1 = rnorm(5), x2 = rnorm(5))

> df
           x         x1          x2
1  1.2222897  0.3904347 -0.05835815
2 -1.7002094 -1.5195555 -0.79265835
3  0.5570183 -1.3191265  0.26198408
4 -0.2457016  0.1461557 -0.05567788
5 -0.7689870 -0.6361940 -0.80780107

library(plyr)
library(reshape2)
library(ggplot2)
# melting the data.frame turns your data.frame from wide to tall
# d_ply takes a data frame, applies a function each variable (in this case column) 
# creates a plot, writes it to disk but returns nothing.
d_ply(melt(df), .(variable), function(x){
    pl <- qplot(x$value, geom = "histogram", main = unique(x$variable))
    # Change the png to jpg, eps or pdf if you prefer a different format
    ggsave(pl, file = paste0(unique(x$variable),".png"))
    })

# Now we can see that my working dir has 3 plots, each named after a column
> dir(pattern = "png")
[1] "x.png"  "x1.png" "x2.png"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM