Home > front end >  How to print some column by for loop in R
How to print some column by for loop in R

Time:07-06

I've some table in R (my_df) with the columns: "name", "city", country".

I also have a vector that holds some of the columns names:

name_vec = c("city", "country")

I want to print all the current column in name_vec by for loop:

for (i in name_vec ){
print(my_df$i)
}

Now it doesn't work well, How can I fix it?

Important - I want to use just in my variable "i" - without any number or string

TY

CodePudding user response:

Let suppose we have this data.frame

# Define a data.frame
  df <- data.frame(city=c("Madrid", "Paris", "London", "Barcelona"),
                   country=c("SPA", "FRA", "UK", "SPA"))
# Column names
  c.name <- c("city", "country")

You can use the following code in order to get each column

# Print each column
  for (i in 1:length(c.name)){
    print(df[,c.name[i]])
  }


# What you get . . . 
  [1] "Madrid"    "Paris"     "London"    "Barcelona"
  [1] "SPA" "FRA" "UK"  "SPA"
  •  Tags:  
  • r
  • Related