I am trying to create 2 new variables for all the elements/data frames in a large list, similar to what it was done in this post How to create in R new variable for each element in a list of data frames with the name of data frame and its value equal to position of the element. But the elements name in my list are more complex. These are two examples of the names - "mean_AST_wind084_ROS007", "mean_AST_wind177_ROS01". The variables I want to create are "wind" and "ROS" and the values should be number that is next to the word in the element name. Here is an example what the elements should look like after creating the two variables:
list_df
$mean_AST_wind177_ROS01
temp wind ROS
1 25 1.77 0.1
2 50 1.77 0.1
3 70 1.77 0.1
4 66 1.77 0.1
5 67 1.77 0.1
$mean_AST_wind084_ROS007
temp wind ROS
1 12 0.84 0.07
2 20 0.84 0.07
3 25 0.84 0.07
4 33 0.84 0.07
5 23 0.84 0.07
I tried to use the code from the other post to create each variable at a time (df<-lapply(seq(list_df), function(x) "[[<-"(dfs[[x]], paste0("wind", x), value = x))). But it didn't work, probably because it is not correct. Any help how I could do that is very much appreciated! Thank you!
CodePudding user response:
We could use imap
library(purrr)
library(stringr)
list_df <- imap(list_df, ~ .x %>%
mutate(wind = as.numeric(str_replace(.y,
".*wind(\\d)(\\d ).*", "\\1.\\2")),
ROS = as.numeric(str_replace(.y, ".*ROS(\\d)(\\d ).*", "\\1.\\2"))))
-output
list_df
$mean_AST_wind177_ROS01
temp wind ROS
1 25 1.77 0.1
2 50 1.77 0.1
3 70 1.77 0.1
4 66 1.77 0.1
5 67 1.77 0.1
$mean_AST_wind084_ROS007
temp wind ROS
1 12 0.84 0.07
2 20 0.84 0.07
3 25 0.84 0.07
4 33 0.84 0.07
5 23 0.84 0.07
Or in base R
list_df <- Map(function(dat, nm) {
transform(dat, wind = as.numeric(sub(".*wind(\\d)(\\d )_.*",
"\\1.\\2", nm)),
ROS = as.numeric(sub(".*ROS(\\d)(\\d )", "\\1.\\2", nm)))
}, list_df, names(list_df))
-output
list_df
$mean_AST_wind177_ROS01
temp wind ROS
1 25 1.77 0.1
2 50 1.77 0.1
3 70 1.77 0.1
4 66 1.77 0.1
5 67 1.77 0.1
$mean_AST_wind084_ROS007
temp wind ROS
1 12 0.84 0.07
2 20 0.84 0.07
3 25 0.84 0.07
4 33 0.84 0.07
5 23 0.84 0.07
data
list_df <- list(mean_AST_wind177_ROS01 = structure(list(temp = c(25L, 50L,
70L, 66L, 67L)), row.names = c("1", "2", "3", "4", "5"), class = "data.frame"),
mean_AST_wind084_ROS007 = structure(list(temp = c(12L, 20L,
25L, 33L, 23L)), row.names = c("1", "2", "3", "4", "5"),
class = "data.frame"))