简体   繁体   中英

Create Loop for Box Plots in R

I have a dataset that contains both numeric and categorical values. I am trying to create box plots to visually identify outliers for each numeric column in my dataset. The below code works to do this, but it is very clunky and I would not want to use this code with even more variables. I am looking for a way to use a loop to create box plots using a loop in R.

Here is the clunky code that works without a loop:

#Using Boxplots, check for outliers in each in each float or integer value column. 

b <-boxplot(df$item1, main = 'item1')
b <-boxplot(df$item2, main = 'item2')
b <-boxplot(df$item3, main = 'item3')
b <-boxplot(df$item4, main = 'item4')
b <-boxplot(df$item5, main = 'item5')
b <-boxplot(df$item6, main = 'item6')
b <-boxplot(df$item7, main = 'item7')
b <-boxplot(df$item8, main = 'item8')
b <-boxplot(df$item9, main = 'item9')
b <-boxplot(df$item10, main = 'item10')
b <-boxplot(df$item11, main = 'item11')
b <-boxplot(df$item12, main = 'item12')
b <-boxplot(df$item13, main = 'item13')
b <-boxplot(df$item14, main = 'item14')
b <-boxplot(df$item15, main = 'item15')
b <-boxplot(df$item16, main = 'item16')

In python the code would be:

outliers = ['Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Item6', 'Item7', 'Item8', 'Item9', 'Item10', 'Item11', 'Item12', 'Item13', 'Item14', 'Item15', 'Item16']

i=0 
while i < len(outliers):
    sns.boxplot(x = outliers[i], data = df)
    plt.show()
    i = i + 1

(I am looking for something similar in R!) Thank you!

Using a for loop to loop over the columns and a minimal reprex based on mtcars you could do

outliers <- c("mpg", "hp")

for (i in outliers) {
  boxplot(mtcars[i], main = i)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM