I have a list of data frames in R. What I need to do is apply a function to each data file, in this case delete special characters and return a list of data.
Using lapplyand as.data.frame, the following works perfectly and provides exactly what I need:
my_df =data.frame(names = seq(1,10), chars = c("abcabc!!", "abcabc234234!!"))
my_list = list(my_df, my_df, my_df)
List of 3
$ :'data.frame': 10 obs. of 2 variables: ...
new_list <- lapply(my_list, function(y) as.data.frame(lapply(y, function(x) gsub("[^[:alnum:][:space:]']", "", x))))
List of 3
$ :'data.frame': 10 obs. of 2 variables:
..$ names: Factor w/ 10 levels "1","10","2","3",..: 1 3 4 5 6 7 8 9 10 2
..$ chars: Factor w/ 2 levels "abcabc","abcabc234234": 1 2 1 2 1 2 1 2 1 2
$ :'data.frame': 10 obs. of 2 variables:
..$ names: Factor w/ 10 levels "1","10","2","3",..: 1 3 4 5 6 7 8 9 10 2
..$ chars: Factor w/ 2 levels "abcabc","abcabc234234": 1 2 1 2 1 2 1 2 1 2
$ :'data.frame': 10 obs. of 2 variables:
..$ names: Factor w/ 10 levels "1","10","2","3",..: 1 3 4 5 6 7 8 9 10 2
..$ chars: Factor w/ 2 levels "abcabc","abcabc234234": 1 2 1 2 1 2 1 2 1 2
But I am wondering if there is a more efficient way that does not require nested lapply. Perhaps another apply-family function that returns elements as a data frame?
source
share