Reputation: 11
I try to run a chunk of code multiple times (t1-t13). Since all the variable names start with the name of the concerning timepoint, I tried to write a function in which I wanted to simply replace the “t1” in the variable name, e.g., t1_ls_3. To do so, I used the paste function to convert the following chunk of code into a function, where only the timepoint should be replaced. A short example:
I need a way to change t1 in this line:
data$t1_ls_3 <- 11
I tried this out and it worked:
data[paste(“t1”, "ls_3", sep = "_")] <- 11
data <- data[paste(“t1”, "ls_3", sep = "_")]
Then I tried to write it as a function:
func_replace <- function(x = “time”) {
data[paste(“time”, "ls_3", sep = "_")] <- 11
data <- data[paste(“time”, "ls_3", sep = "_")]
}
func_replace (x = “t1“)
However, all R does when I run the function is to put a new variable into the data frame, time_ls_3 and does not change the actual variable t1_ls_3. Do you have any idea what the problem is or how I can exchange parts of a variable name in a function? I know that I could work around the problem by using a long-format data set. But I would like to know how to exchange parts of a variable in a function in general.
Upvotes: 1
Views: 333
Reputation: 24838
Your fundamental misunderstanding seems to be about character strings and symbols.
You define a character string in R with "
or '
. Thus the following:
"time"
is a character string with the word time in it.
In contrast, symbols are names that can refer to objects in R. You can create a symbol (pointing to an object) holding a time called time like this:
time <- "03:00"
When you type time
at the console, you get back the character string:
time
#"03:00"
Therefore, when you try to use paste
with "time"
, you're going to get the same result no matter what:
paste("time", "ls_3", sep = "_")
#[1] "time_ls_3"
Instead, you seem to want to use x
which is the symbol your function is assigning "t1"
to.
Perhaps your data looks something like this:
data <- setNames(data.frame(t(rep(0,5))),sapply(1:5,\(x)paste0("t",x,"_ls_3")))
data
# t1_ls_3 t2_ls_3 t3_ls_3 t4_ls_3 t5_ls_3
#1 0 0 0 0 0
The last problem is that assignments inside functions only work in the function environment, so you need to use the <<-
operator.
func_replace <- function(x = NULL) {
data[paste(x, "ls_3", sep = "_")] <<- 11
}
func_replace(x = “t1“)
data
# t1_ls_3 t2_ls_3 t3_ls_3 t4_ls_3 t5_ls_3
#1 11 0 0 0 0
Upvotes: 2