r - How do I loop through strings like they're column names? -



r - How do I loop through strings like they're column names? -

sample code

df <- read.csv('datafile.csv') columnnames <- c('col1','col2')

i want loop through columnnames , print values. basically, want same values i'd if entered console df$col1 or df$col2. how do that?

[ takes strings, $ doesn't.

for (cname in names(mtcars)) { print(mtcars[, cname]) }

see also:

> fortunes::fortune(343)

sooner or later r beginners bitten convenient shortcut. r newbie, think of r bank account: overuse of $-extraction can lead undesirable consequences. it's best acquire '[[' , '[' habit early. -- peter ehlers (about utilize of $-extraction) r-help (march 2013)

as @buckminster points out, [ vectorized, might not need loop:

cols = c("mpg", "disp", "cyl") mtcars[, cols]

r

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -