简体   繁体   English

在循环中检查特定的对象名称

[英]check for a particular object name in a loop

I have a loop with a lot of data frames. 我有很多数据帧的循环。

When I come to certain data frames my logic needs to adjust. 当我谈到某些数据帧时,我的逻辑需要调整。 I'm looking for a while to make a TRUE/FALSE statement out of this, but I'm not sure exactly how to pull this off. 我正在寻找一段时间来做出一个TRUE / FALSE陈述,但是我不确定如何实现这一点。

I want to convert the actual name of the variable into the text of the variable. 我想将变量的实际名称转换为变量的文本。

my_list_of_dfs = list(iris,mtcars)

for (i in my_list_of_dfs){ if i =='iris'{ print('this works') } }

Try a named list instead 尝试使用命名列表

# Created a named list instead...
my_list_of_dfs = list('iris'=iris, 'mtcars'=mtcars)

# check the names
names(my_list_of_dfs)
# [1] "iris"   "mtcars"

for (i in names(my_list_of_dfs) ) {
  if (i =='iris') {
    print('this works')
  }
  print (my_list_of_dfs[i]) # You can access data-frame like this...
}

BTW, you also forgot the brackets around the condition in your if statement 顺便说一句,您还忘记了if语句中条件的括号

An addition to answer by @Ismail (so please upvote that answer if you agree with the idea of using a named list), is to create a function that generates a named list for you. @Ismail回答的一个补充(因此,如果您同意使用命名列表的想法,请对此答案进行投票)是创建一个为您生成命名列表的函数。 That is, instead of explicitly typing something like list('iris'=iris, 'mtcars'=mtcars) , the following function will take R objects, combine them in a list, and name the list with the objects: 也就是说,以下函数不会显式键入诸如list('iris'=iris, 'mtcars'=mtcars)list('iris'=iris, 'mtcars'=mtcars)使用R对象,将它们组合在一个列表中,然后使用这些对象命名该列表:

named_list <- function(...) {
  .l <- list(...)
  .names <- deparse(substitute(list(...)))
  .names <- strsplit(gsub("list\\(|\\)| ", "", .names), ",")[[1]]
  names(.l) <- .names
  .l
}

x <- 3
y <- data.frame(a=1,b=2)
named_list(x, y)
#> $x
#> [1] 3
#> 
#> $y
#>   a b
#> 1 1 2

my_list_of_dfs  <- named_list(iris, mtcars)
names(my_list_of_dfs )
#> [1] "iris"   "mtcars"

Can follow @Ismail answer from here with something like: 可以从这里跟随@Ismail答案,例如:

for (i in names(my_list_of_dfs )) {
  if (i == "iris")
    print(names(my_list_of_dfs[[i]]))
  else
    print ("This is NOT iris")
}
#> [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width" "Species"     
#> [1] "This is NOT iris"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM