简体   繁体   中英

Iterating through variables (columns) in a dataframe in R

I am a total beginner in R, so this might be an obvious question. I have a dataframe with 129 variables, some numeric, some string. Basically, I am trying to loop through each variable to calculate the mean/mode(depending on the variable), standard dev (if applicable), and frequency, and have it some sort of nice package I could export. I have tried using a for loop, but I can only get it to go through rows, not columns. Anyone have any suggestions?

Thanks!!

You can use a for-loop across columns too.

# Considering only 8 rows and using numeric and character cols for demonstration 
iris_new = iris[1:8,]   
iris_new$Species = as.character(iris_new$Species)

for(i in iris_new){  
  print(i)  
}

 [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0   
 [1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 3.4   
 [1] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5   
 [1] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2   
 [1] "setosa" "setosa" "setosa" "setosa" "setosa" "setosa" "setosa" "setosa"

colnames(my_dataframe) yields a vector containing the column names of 'my_dataframe'. You can iterate over the elements, here's an example printing the first element of each column:

for (the_column in colnames(m))
{
    print(my_dataframe[,c(the_column)][1])
}

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