在循环中使用对象名称 [英] use object name in a loop
问题描述
.df
命令的for循环。现在,我想在我的循环中的粘贴
中使用数据框的名称作为后缀
。有没有办法使用 for(.df in [list]){
命令,我可以减去名字的数据框目前在 .df
内循环? 说我有这个列表有三个数据帧,
a< - list(A = data.frame(a = runif(2),b = runif(2)) ,
B = data.frame(a = runif(2),b = runif(2)),
C = data.frame(a = runif(2),b = runif(2)) )
a
$ A
ab
1 0.2833226 0.6242624
2 0.1741420 0.1707722
$ bab
1 0.55073381 0.6082305
2 0.08678421 0.5192457
$ C
ab
1 0.02788030 0.1392156
2 0.02171247 0.7189846
现在,我想使用这个循环,
for(.df in a){
print(['command I do not知道'])
}
然后有[命令我不知道]打印出A,B,C(即 .df
中的数据框的名称。
我可以这样做吗?
更新2012-04-28 20:11:58 PDT
这是一个剪辑,我期望的形式我的输出使用简单从
for(.df in a){
print(['command我不知道'](a))
}
[1]A
[1]B
[1]C
我可以获得这个使用,
for(x in names(a)){
print(x)
}
但是由于我正在做的事情的性质,我想在我的for-中使用 for(.list in [list]){
循环。
要提取名称和值,您不能循环遍历值。您可以循环索引或名称:
#循环索引(更快,更麻烦)
ns < - 名称(a)
(i在seq_along(a)){
v < - a [[i]]#提取值
n < - ns [[i]] #提取名称
cat(n,:\\\
)
str(v)
}
#循环名称(容易但较慢)
for(n in names(a)){
v < - a [[n]]#extract value
cat(n,:\\\
)
str )
}
...循环名称和提取值可能很慢向量(它有n ^ 2时间复杂度)。
I'm merging some data frames that are stored in a list. For that purpose I'm using a for-loop with a .df
command. Now, I would like to use the name of the data frame as suffixes
in a paste
inside my loop.
Is there a way, using the for ( .df in [list]) {
command that I can subtract the name of the data frame currently in .df
inside the loop?
Say I have this list with three data frames,
a <- list(A = data.frame(a=runif(2), b=runif(2)),
B = data.frame(a=runif(2), b=runif(2)),
C = data.frame(a=runif(2), b=runif(2)))
a
$A
a b
1 0.2833226 0.6242624
2 0.1741420 0.1707722
$B
a b
1 0.55073381 0.6082305
2 0.08678421 0.5192457
$C
a b
1 0.02788030 0.1392156
2 0.02171247 0.7189846
Now, I would like to use this loop,
for ( .df in a) {
print(['command I do not know about'])
}
and then have the [command I do not know about] print out A, B, C (i.e. the name of the data frame in .df
).
Can I do that?
Update 2012-04-28 20:11:58 PDT
Here is a snipped of what I expect form my output using the simple loop from above,
for ( .df in a) {
print(['command I do not know about'](a))
}
[1] "A"
[1] "B"
[1] "C"
I could obtain this using,
for (x in names(a)) {
print(x)
}
but due to the nature of what I am doing I would like to use the for ( .df in [list]) {
command in my for-loop.
To extract both the name and the value you can't loop over the values. You can loop over either the indices or the names:
# Loop over indices (faster, more cumbersome)
ns <- names(a)
for(i in seq_along(a)) {
v <- a[[i]] # extract value
n <- ns[[i]] # extract name
cat(n, ": \n")
str(v)
}
# Loop over names (easy but slower)
for(n in names(a)) {
v <- a[[n]] # extract value
cat(n, ": \n")
str(v)
}
...looping over names and extracting values can be very slow for long vectors (it has n^2 time complexity).
这篇关于在循环中使用对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!