R - Programming: How to loop through a list of dataframes and manipulate specific columns within each?
lapply, list, r
Solution
The third line inside that functions should be:
x[, c(1:7, 9:14)] <- lapply( x[, c(1:7, 9:14)] , factor)
And you should `return(x)` at the end.
Problem
So I have three data frames, each with 14 columns. ``` iowa <- data.frame() #Has 14 columns; let's say 600 records maine <- data.frame() #Has same 14 columns; let's say 700 records texas <- data.frame() #Has same 14 columns; let's say 900 records ``` I place those data frames within a list, ``` state_List <- list(iowa, maine, texas) ``` I then want to change two columns (called "State_Date" and "US_Date") within each data frame within the state_List to date formats, and I would like to change all columns except to one as factors. I have written the following: ``` state_List <- lapply(state_List, function(x){ x$State_Date <- as.Date(x$State_Date, format = "%m/%d/%Y") x$US_Date <- as.Date(x$US_Date, format = "%m/%d/%Y") x[, c(1:7, 9:14)] <- as.factor(x[, c(1:7, 9:14)] } ) ``` The error I receive is ``` Error in sort.list(y) : 'x' must be atomic for 'sort.list' Have you called 'sort' on a list? ``` This error is due to the as.factor part. However, if I get rid of the last evaluation of the function called in lapply, and just keep the two that change the class of the date fields, what I get is: - A list where the 3 names of the data frames it contained are lost - Each data frame in the list, or should I say each slot for a data frame in the list is now filled with the US_Date column for that state. What I'd like is: - A list with 3 data frames (that retains the name of the data frames) - Within each data frame, the two fields, State_Date and US_Date have dates that have been formatted as such - All columns except for column 8 to be formatted as factors Thank you for your help! ** CORRECT CODE BELOW SHOWS WHAT I SHOULD HAVE DONE BASED ON THE RESPONSE: ``` state_List <- list(iowa = iowa, maine = maine, texas = texas) state_List <- lapply(state_List, function(X){ x$State_Date <- as.Date(x$State_Date, format = "%m/%d/%Y") x$US_Date <- as.Date(x$US_Date, format = "%m/%d/%Y") x[, c(1:7, 9:14)] <- lapply( x[, c(1:7, 9:14)] , factor) return(x) } ) ```