Home > Enterprise >  Call of dataframe columns in R
Call of dataframe columns in R

Time:11-30

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?

CodePudding user response:

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

iris

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

CodePudding user response:

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="")])
}
  • Related