[英]binding objects with a string and getting the column names with the name of the object in R
我有多個具有公共字符串的對象
resultsPetal.Length
resultsPetal.Width
resultsSetal.Length
resultsSetal.Width
當我對它們使用 cbind 時,我得到了這個列表
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"
但是,我有多個對象並且想加入它們而不必為每個對象寫一行,所以我使用了
test=do.call(cbind, lapply(ls(pattern ="result"), get))
這讓我
[,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"
如您所見,我丟失了 object 名稱,而且我完全不知道如何解決這個問題。 我能做什么?
這是可重復性的完整代碼
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))
您可以使用幾種方法:
使用mget
:
do.call(cbind, mget(ls(pattern = 'result')))
使用sapply
:
sapply(ls(pattern ="result"), get)
為列表命名:
l <- ls(pattern ="result")
do.call(cbind, lapply(setNames(l,l), get))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.