TFC
TFC

Reputation: 67

Call of dataframe columns in R

I am currently looking for a solution to call each column of a data frame in a for loop like this:


         V1     V2     V3       V4  V5   V6    V7   V8    V9   V10
Activity dep10  out10  dep500  -5  -15  -90   +45  +20   +32   out100
for (i in 0:length(df)) {
  newDf$rowOne <<- df$V(value of i)
}

I want to call V1, then V2, then V3 etc... using the value of i so I can modify or use the content of the df data frame.

Any suggestions?

Upvotes: 1

Views: 194

Answers (2)

Yacine Hajji
Yacine Hajji

Reputation: 1449

With paste(), you can call your columns even if they aren't sorted. The idea is to paste the name "V" with the ith value of variable.

Here, you can loop over each column by just specifying the "i" value from the loop

for(i in 1:ncol(df)){
     print(df[,paste("V",i,sep="")])
}

Upvotes: 2

Quixotic22
Quixotic22

Reputation: 2924

A cleaner solution would be to loop through colnames like so:

iris

for (i in colnames(iris)){
  print(head(iris[i]))
}

Upvotes: 5

Related Questions