First off - I apologise for the badly phrased question, if you have any more appropriate suggestions for it I'm all ears!
I have written a function that adds a new variable into my df based on what the object is called. For example, I have x_data, and when I put it into my function, a new variable called x_or_y is created, with all entries showing "x". You guessed it - there is also a y_data, that when plugged into the function it creates the same variable x_or_y and fills it with "y"
I'm having some issues however when I have a list of dfs (x_data and y_data) and I use lapply() to the list - it just returns the same letter for all. See below my example.
Example:
set.seed(123)
x_data <- data.frame(A = rnorm(20),
B = rnorm(20))
y_data <- data.frame(A = rnorm(20),
B = rnorm(20))
Function for "x or y":
add_x_or_y <- function(z) {
z$x_or_y <- ifelse(grepl(pattern = "x",
deparse(substitute(z)), fixed = TRUE),
"x", "y")
z
}
So trying the function out by itself:
head(add_x_or_y(x_data),3)
A B x_or_y
1 -0.56047565 -1.0678237 x
2 -0.23017749 -0.2179749 x
3 1.5587083 -1.0260044 x
head(add_x_or_y(y_data),3)
A B x_or_y
1 -0.6947070 0.3796395 y
2 -0.2079173 -0.5023235 y
3 -1.2653964 -0.3332074 y
Okay, so that works - but in real life I have about 20 different dfs that I need to put through the function. That's a lot of wasted space writing it each time, so let's make a list and use lapply().
x_y_list <- list(x_data = x_data,
y_data = y_data)
x_y_list <- lapply(x_y_list, add_x_or_y)
head(x_y_list$x_data,3)
A B x_or_y
1 -0.5604756 -1.0678237 y
2 -0.2301775 -0.2179749 y
3 1.5587083 -1.0260044 y
head(x_y_list$y_data,3)
A B x_or_y
1 -0.6947070 0.3796395 y
2 -0.2079173 -0.5023235 y
3 -1.2653964 -0.3332074 y
It didn't work! :( The first one should have "x"'s in the x_or_y variable. I'm sure it's a really really simple solution here, but I cannot seem to find it - please help Stack Overflow!
names(x_y_list)to a modified function to achieve the same behaviorprint(deparse(substitute(z)))as the first instruction of the function and see what is happening.deparse(substitute(z))is even needed.print(), this is helping to see what's going on. The function is returning"X[[i]]""X[[i]]"which means it's not taking the name of each element in the list, just the subscript. Confused why it shows a capital "X" though?