I have multiple objects with a common string
resultsPetal.Length
resultsPetal.Width
resultsSetal.Length
resultsSetal.Width
and when I use cbind on them, I get this list
resultSepal.Length
statistic 138.9083
parameter Numeric,2
p.value 1.505059e-28
method "One-way analysis of means (not assuming equal variances)"
data.name "dat[, i] and dat$Species"
resultSepal.Width
statistic 45.01204
parameter Numeric,2
p.value 1.432735e-14
method "One-way analysis of means (not assuming equal variances)"
data.name "dat[, i] and dat$Species"
However, I have multiple objects and would like to join them without having to write a line for each, so I used
test=do.call(cbind, lapply(ls(pattern ="result"), get))
which gets me
[,1]
statistic 1828.092
parameter Numeric,2
p.value 2.693327e-66
method "One-way analysis of means (not assuming equal variances)"
data.name "dat[, i] and dat$Species"
[,2]
statistic 1276.885
parameter Numeric,2
p.value 4.138739e-64
method "One-way analysis of means (not assuming equal variances)"
data.name "dat[, i] and dat$Species"
[,3]
statistic 138.9083
parameter Numeric,2
p.value 1.505059e-28
method "One-way analysis of means (not assuming equal variances)"
data.name "dat[, i] and dat$Species"
[,4]
statistic 45.01204
parameter Numeric,2
p.value 1.432735e-14
method "One-way analysis of means (not assuming equal variances)"
data.name "dat[, i] and dat$Species"
As you can see, I have lost the object name and I have absolutely no clue how to work around this. What can I do?
Here is the full code for reproducibility
dat <- iris# remove one level to have only two groups
#dat <- subset(dat, Species != "setosa")
dat$Species <- factor(dat$Species)# boxplots and t-tests for the 4 variables at once
for (i in 1:4) { # variables to compare are variables 1 to 4
boxplot(dat[, i] ~ dat$Species, # draw boxplots by group
ylab = names(dat[i]), # rename y-axis with variable's name
xlab = "Species"
)
print(oneway.test(dat[, i] ~ dat$Species)) # print results of t-test
assign(paste0("result", names(dat[i])), (oneway.test(dat[, i] ~ dat$Species)))
}
test=cbind(resultSepal.Length, resultSepal.Width)
test=do.call(cbind, lapply(ls(pattern ="result"), get))
There are few approaches you could use:
Use mget
:
do.call(cbind, mget(ls(pattern = 'result')))
Use sapply
:
sapply(ls(pattern ="result"), get)
Give names to the list:
l <- ls(pattern ="result")
do.call(cbind, lapply(setNames(l,l), get))