If I understand your question:
Created three parti
datasets
parti1 <- as.data.frame(matrix(5:25, ncol=3, dimnames=list(NULL, c("Col1", "Col2", "Time"))))
parti2 <- as.data.frame(matrix(1:15, ncol=3, dimnames=list(NULL, c("Col1", "Col2", "Time"))))
parti3 <- as.data.frame(matrix(1:15, ncol=3, dimnames=list(NULL, c("Col1", "Col2", "Time"))))
Used ls
and mget
to get the values of the datasets
For example,
ls(pattern="^parti") #gives you the created object names that starts with `parti` in the working environment.
#[1] "parti1" "parti2" "parti3"
lst1 <- mget(ls(pattern="^parti")) #mget will return a list of values of each `parti` object
If you need to change the column Time
to 1 for each datasets, there are a couple of ways. The methods below created the columns within the list environment. To change your original datasets, you have to do assign
or list2env
Map(function(x, y) {x[,"Time"] <- y; x}, lst1, 1)
Or
lapply(lst1, function(x) {x$Time <-1; x}) #I am changing the existing `Time` column to 1 by using the assignment operator `<-`.
If you want to create a new column, just do:
lapply(lst1, function(x) {x$Time1 <-1; x})
Update
If you need to change/create columns in the original dataset,
partin <- paste0("parti", 1)
assign(partin, `[[<-`(get(partin),'Time', value=1))
The above method take the string
i.e. partin
as first argument, and uses the replacement function [[<-
. Then to get the values of partin
use get
. The next argument is the column to modify or create ie. Time
and assign a value of 1
to that column.
parti1
# Col1 Col2 Time
#1 5 12 1
#2 6 13 1
#3 7 14 1
#4 8 15 1
#5 9 16 1
#6 10 17 1
#7 11 18 1
For multiple datasets, to change/create a existing column/new column, you could use a for
loop with assign
or use list2env
partin1 <- paste0("parti", 1:3)
for(i in seq_along(partin1)){
assign(partin1[i], `[[<-`(get(partin1[i]), 'Time1', value=5)) #creating a new column
}
parti2
# Col1 Col2 Time Time1
#1 1 6 11 5
#2 2 7 12 5
#3 3 8 13 5
#4 4 9 14 5
#5 5 10 15 5
This could be also done using list2env
list2env(lapply(mget(partin1),
function(x) {x$Time2 <- 10 ;x}), envir=.GlobalEnv)
But, I would suggest doing the analysis in a list rather than creating objects.
Update2
Method using eval(parse
partin <- paste0("parti", 1)
toAssign <- paste0(partin, "[,'Time3']")
str1 <- paste0(toAssign, "<-", 15)
eval(parse(text=str1))
parti1
# Col1 Col2 Time Time3
#1 5 12 19 15
#2 6 13 20 15
#3 7 14 21 15
#4 8 15 22 15
#5 9 16 23 15
#6 10 17 24 15
#7 11 18 25 15
Using the example dataset provided
toAssign <- paste0("Oldtbl", "[, 'Time']")
str1 <- paste0(toAssign, "<-", "'10:15'")
eval(parse(text=str1))
Oldtbl
# Name Gender Hobbies Time
#1 name FALSE singing 10:15
data
Oldtbl <- structure(list(Name = "name", Gender = FALSE, Hobbies = "singing",
Time = "10:15"), row.names = c(NA, -1L), .Names = c("Name",
"Gender", "Hobbies", "Time"), class = "data.frame")