使用paste0、get/eval和parse在for循环中为列表命名。

huangapple go评论58阅读模式
英文:

naming lists within for loop using paste0 and get/eval, parse

问题

I understand that you want assistance with the code translation. Here is the translated code:

直接回答问题。
[as1_list][1]

我试图使用name()和paste()来为列表中的数据框命名,
但我在赋值时遇到了问题。

num_fu <- c('1','2','3','4','5','6','7','8','9')
as <- data.frame()

for (i in num_fu){
    assign(paste0("flnames", i), list.files(path = paste0("C:/Users/thepr/Documents/data/as", i), pattern = "\\.csv", full.names = TRUE))
    assign(paste0("as", i, "_list"), lapply(get(paste0("flnames", i)),
                                               function(x){base::as.data.frame(read.csv(x))}))
   
    nm <- gsub(".csv", "", basename(get(paste0("flnames", i)))) %>% str_sub(., 1,6)
}

nm 返回:
> nm
 [1] "as1_01" "as1_02" "as1_03" "as1_04" "as1_05" "as1_07" "as1_08" "as1_09" "as1_11" "as1_13"
[11] "as1_14" "as1_15" "as1_99"


names(as1_list) 返回
> names(as1_list)
NULL

我尝试了 get(paste0 ...
names(get(paste0("as", i, "_list"))) <- nm

这会返回错误:
Error in names(get(paste0("as", i, "_list"))) <- nm :
target of assignment expands to non-language object

所以我尝试了

names(eval(parse(text = paste0("as", i, "_list")))) <- nm

但是出现了这个错误:
Error in names(eval(parse(text = paste0("as", i, "_list")))) <- nm :
target of assignment expands to non-language object

我还尝试了使用 assign() 函数,使用上述两个代码中的任何一个。

assign(names(get(paste0("as", i, "_list"))), nm)

返回:
Error in assign(names(get(paste0("as", i, "_list"))), nm) :
invalid first argument

assign(names(eval(parse(text = paste0("as", i, "_list")))), nm)

返回:
Error in assign(names(eval(parse(text = paste0("as", i, "_list")))), nm) :
invalid first argument

请帮助。谢谢。


I've translated the code for you. If you have any specific questions or need further assistance, please let me know.

<details>
<summary>英文:</summary>

Straight to the question.
[as1_list][1]

I am trying to name data.frames in a list using name() and paste()
but I am having trouble assigning them

num_fu = c('1','2','3','4','5','6','7','8','9')
as <- data.frame()

for (i in num_fu){
assign(paste0("flnames", i), list.files(path = paste0("C:/Users/thepr/Documents/data/as", i), pattern = "\.csv", full.names = TRUE))
assign(paste0("as", i, "_list"), lapply(get(paste0("flnames", i)),
function(x){base::as.data.frame(read.csv(x))}))

       nm &lt;- gsub(&quot;.csv&quot;, &quot;&quot;, basename(get(paste0(&quot;flnames&quot;, i)))) %&gt;% str_sub(., 1,6)

```nm``` returns 
&gt; nm
 [1] &quot;as1_01&quot; &quot;as1_02&quot; &quot;as1_03&quot; &quot;as1_04&quot; &quot;as1_05&quot; &quot;as1_07&quot; &quot;as1_08&quot; &quot;as1_09&quot; &quot;as1_11&quot; &quot;as1_13&quot;
[11] &quot;as1_14&quot; &quot;as1_15&quot; &quot;as1_99&quot;

and

```names(as1_list)``` returns

> names(as1_list)
NULL


I tried get(paste0 ...

names(get(paste0("as", i, "_list"))) <- nm


this returns error:
Error in names(get(paste0(&quot;as&quot;, i, &quot;_list&quot;))) &lt;- nm : 
  target of assignment expands to non-language object

so I tried

names(eval(parse(text = paste0("as", i, "_list")))) <- nm


and this occurred:
Error in names(eval(parse(text = paste0(&quot;as&quot;, i, &quot;_list&quot;)))) &lt;- nm : 
  target of assignment expands to non-language object


I have also tried assign() function using both of the above codes.

assign(names(get(paste0("as", i, "_list"))), nm)

Returns:
Error in assign(names(get(paste0(&quot;as&quot;, i, &quot;_list&quot;))), nm) : 
  invalid first argument

and

assign(names(eval(parse(text = paste0("as", i, "_list")))), nm)

Returns:
Error in assign(names(eval(parse(text = paste0(&quot;as&quot;, i, &quot;_list&quot;)))), nm) : 
  invalid first argument

Please help. Thank you.


  [1]: https://i.stack.imgur.com/YTMec.png

</details>


# 答案1
**得分**: 1

I learned that it is mostly a bad idea to use `assign()` within `for` loops.

只需学会使用R的向量化特性,让它发挥作用!

例如,考虑将`for`循环的结果存储在一个单一列表中。您仍然可以稍后将列表内容转换为单个对象:https://stackoverflow.com/questions/17697239/unlist-a-list-of-dataframes

我认为,您试图实现的目标是批量读取.csv文件并重命名它们。请查看这里:https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once

<details>
<summary>英文:</summary>

I learned that it is mostly a bad idea to use `assign()` within `for` loops.

Just learn to use the vectorised nature of R to make it shine!

For example, consider storing the results of your `for` loop in a single list. You can still convert the list contents to single objects later on: https://stackoverflow.com/questions/17697239/unlist-a-list-of-dataframes 

I think, what you are trying to accomplish is to batch read .csv-files and renaming them. Have a look here: https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once








</details>



# 答案2
**得分**: 1

根据您的评论,以下内容将为您提供一个数据框列表,每个数据框来自一个单独的CSV文件(以"as"开头),并以不包括扩展名的文件名命名:

```R
data_dir <- 'C:/Users/thepr/Documents/data/'
file_names <- list.files(data_dir, pattern = 'as.*\\.csv')

list_of_dataframes <- 
  file_names |>
  Map(f = \(fn) read.csv(file.path(data_dir,fn))) |>
  setNames(nm = gsub('\\.csv', '', file_names))

请注意使用Map来操作一个列表(在本例中是文件名列表),以避免使用任何for循环(通常在R中是个好主意)。

英文:

As specified in your comment, the following will give you a list of dataframes, each from a single CSV-file (starting with "as") and named with the filename excluding extension:

data_dir &lt;- &#39;C:/Users/thepr/Documents/data/&#39;
file_names &lt;- list.files(data_dir, pattern = &#39;as.*\\.csv&#39;)

list_of_dataframes &lt;- 
  file_names |&gt;
  Map(f = \(fn) read.csv(file.path(data_dir,fn))) |&gt;
  setNames(nm = gsub(&#39;\\.csv&#39;, &#39;&#39;, file_names))

Note the use of Map to operate on a list (of file names, in this case) and avoid any for loop (generally a good idea in R).

huangapple
  • 本文由 发表于 2023年5月21日 11:37:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298192.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定