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
Post a Comment