如何在R中使用循环处理重复的代码

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

How to use loops for repetitive code in R

问题

我知道关于这个问题有答案,但它仍然让我感到困惑,因为通常用于更高级的任务,而这是一个非常简单的任务。

我有21个数据框,它们的格式为data_1data_2data_3等。它们都具有相同的列标题,只是行中的值不同。我想要将所有数据框的第一列重命名为“ID”。我一直在使用以下方法:

names(data_1)[1] <- "ID"
names(data_2)[1] <- "ID" #等等

如何创建一个循环来自动处理具有这种模式的所有数据框?

我还有一组命名为df_1df_2df_3等的数据框。df_1具有一个公共列(ID),我想要与data_1进行内部连接,并重复执行data_2和df_2等操作。我一直在使用以下方法:

result_1 <- inner_join(data_1, df_1, by = "ID")
result_2 <- inner_join(data_2, df_2, by = "ID") #等等

如何循环执行这个操作,而不是重复21次?

英文:

I know there are answers out there for this, but it is still confusing me as it is usually for more advanced tasks, and this is a very simple task.

I have 21 data frames that are in the format data_1 data_2 data_3 etc. They all have the same headings, just with different values in the rows. I want to rename column 1 "ID" for all the data frames. I have been using:

names(data_1)[1] &lt;- &quot;ID&quot;
names(data_2)[1] &lt;- &quot;ID&quot; #etc

How can I make a loop to automatically cycle through all the data frames with that pattern?

I have another set of data frames named df_1 df_2 df_3. This df_1 has a common column (ID) that I would like to make an inner join with data_1, and repeat for data_2 and df_2 etc. I was using:

result_1 &lt;- inner_join(data_1, df_1, by = &quot;ID&quot;)
result_2 &lt;- inner_join(data_2, df_2, by = &quot;ID&quot;) #etc

How could I also loop this instead of repeating myself 21 times?

答案1

得分: 2

这是一个很好的实践,将数据作为一个容器(即一个列表)。例如,

 list1 <- mget(ls(pattern = "data_\\d+"))
 list2 <- mget(ls(pattern = 'df_\\d+')) 

然后你可以循环处理这两个列表:

purrr::map(list1, list2, ~inner_join(setnames(.x, c('ID', names(.x)[-1])), .y, by= 'ID'))
英文:

It is a good practice to have the data as a container (i.e. a list). For example,

 list1 &lt;- mget(ls(pattern = &quot;data_\\d+&quot;))
 list2 &lt;- mget(ls(pattern = &#39;df_\\d+&#39;)) 

then you could loop over the two:

purrr::map(list1, list2, ~inner_join(setnames(.x, c(&#39;ID&#39;,names(.x)[-1])), .y, by= &#39;ID&#39;))

huangapple
  • 本文由 发表于 2023年6月8日 07:19:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427654.html
匿名

发表评论

匿名网友

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

确定