Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print some column by for loop in R

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading