英文:
How to use loops for repetitive code in R
问题
我知道关于这个问题有答案,但它仍然让我感到困惑,因为通常用于更高级的任务,而这是一个非常简单的任务。
我有21个数据框,它们的格式为data_1
,data_2
,data_3
等。它们都具有相同的列标题,只是行中的值不同。我想要将所有数据框的第一列重命名为“ID”。我一直在使用以下方法:
names(data_1)[1] <- "ID"
names(data_2)[1] <- "ID" #等等
如何创建一个循环来自动处理具有这种模式的所有数据框?
我还有一组命名为df_1
,df_2
,df_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] <- "ID"
names(data_2)[1] <- "ID" #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 <- inner_join(data_1, df_1, by = "ID")
result_2 <- inner_join(data_2, df_2, by = "ID") #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 <- mget(ls(pattern = "data_\\d+"))
list2 <- mget(ls(pattern = 'df_\\d+'))
then you could loop over the two:
purrr::map(list1, list2, ~inner_join(setnames(.x, c('ID',names(.x)[-1])), .y, by= 'ID'))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论