Often you may want to loop through the column names of a data frame in R and perform some operation on each column. There are two common ways to do this:
Method 1: Use a For Loop
for (i in colnames(df)){ some operation }
Method 2: Use sapply()
sapply(df, some operation)
This tutorial shows an example of how to use each of these methods in practice.
Method 1: Use a For Loop
The following code shows how to loop through the column names of a data frame using a for loop and output the mean value of each column:
#create data frame df <- data.frame(var1=c(1, 3, 3, 4, 5), var2=c(7, 7, 8, 3, 2), var3=c(3, 3, 6, 6, 8), var4=c(1, 1, 2, 8, 9)) #view data frame df var1 var2 var3 var4 1 1 7 3 1 2 3 7 3 1 3 3 8 6 2 4 4 3 6 8 5 5 2 8 9 #loop through each column and print mean of column for (i in colnames(df)){ print(mean(df[[i]])) } [1] 3.2 [1] 5.4 [1] 5.2 [1] 4.2
Method 2: Use sapply()
The following code shows how to loop through the column names of a data frame using sapply() and output the mean value of each column:
#create data frame df <- data.frame(var1=c(1, 3, 3, 4, 5), var2=c(7, 7, 8, 3, 2), var3=c(3, 3, 6, 6, 8), var4=c(1, 1, 2, 8, 9)) #view data frame df var1 var2 var3 var4 1 1 7 3 1 2 3 7 3 1 3 3 8 6 2 4 4 3 6 8 5 5 2 8 9 #loop through each column and print mean of column sapply(df, mean) var1 var2 var3 var4 3.2 5.4 5.2 4.2
Notice that the two methods return identical results.
Related: A Guide to apply(), lapply(), sapply(), and tapply() in R
Thank you zack for your explaining
Hi,
How can I loop across data waves to create a new variable. I have two waves of data. I want to create same variable called xyz_3 and xyz_3. The below code is for wave 3. How can I repeate the same to create xyz_4 for year 4. I want this through loop for both year 3 and 4. A toy data and code is
w_3 w_4 x_3 x_4 y_3 y_4 z_3 z_4
1: 2 2 1 3 50 50 NA NA
2: 1 1 3 5 NA NA NA NA
3: 1 1 2 4 NA NA NA NA
4: NA 1 NA NA NA NA NA NA
5: 1 NA 2 NA NA NA NA NA
6: NA NA NA NA NA NA 0 NA
7: NA 1 NA 5 NA NA NA NA
8: NA 1 NA 4 NA NA NA NA
9: 1 1 3 5 NA NA NA NA
10: 1 1 2 5 NA NA NA NA
The code for year 3 is
dta$xyz_3[(dta$x_3 == 1 & dta$y_3 >= 75 & !is.na(dta$x_3)) |
((dta$x_3 >= 2 & dta$x_3 = 75 & !is.na(dta$y_3)) |
(dta$z_3 >= 30 & !is.na(dta$z_3))] = 25 & dta$y_3 = 25 & dta$y_3 = 10 & dta$z_3 < 30) & !is.na(dta$z_3))] <- 2
dta$xyz_3[(dta$x_3 == 1 & dta$y_3 < 25 & !is.na(dta$x_3)) |
(is.na(dta$x_3) & dta$y_3 < 25 & !is.na(dta$y_3)) |
(dta$z_3 < 10 & !is.na(dta$z_3))] <- 3
dta$xyz_3[is.na(dta$xyz_3) & dta$w_3 == 1] <- 1
dta$xyz_3[is.na(dta$xyz_3) & dta$w_3 == 2] <- 2
How can I do in loop for year 3 & year 4. This will be helpful for many years.