在R中的循环上的各种数据框中创建变量?

时间:2019-05-08 09:50:58

标签: r loops for-loop

我有n个数据框,我想为每个数据框创建一个相同的变量,并用数据框的相应名称填充。


i.e.:

dataframe_a

var 1 | var 2 | var 3 | variable
  x   |   x   |   x   | dataframe_a
  x   |   x   |   x   | dataframe_a
  x   |   x   |   x   | dataframe_a


dataframe_b

var 1 | var 2 | var 3 | variable
  x   |   x   |   x   | dataframe_b
  x   |   x   |   x   | dataframe_b
  x   |   x   |   x   | dataframe_b


dataframe_c

var 1 | var 2 | var 3 | variable
  x   |   x   |   x   | dataframe_c
  x   |   x   |   x   | dataframe_c
  x   |   x   |   x   | dataframe_c


我有两种方法(如下)可以分别为每个数据帧做我想做的事情。但是,如何将以下代码转换为for循环,这样我就不必写100次了?

(我正在使用dplyr :: mutate)


#Take a, b and c as separate dataframes 

dataframe_a$variable <- paste("dataframe_a")
dataframe_b$variable <- paste("dataframe_b")
dataframe_c$variable <- paste("dataframe_c")

#or

dataframe_a %<>% mutate(variable = paste("dataframe_a"))
dataframe_b %<>% mutate(variable = paste("dataframe_b"))
dataframe_c %<>% mutate(variable = paste("dataframe_c"))

我尝试了以下方法,但是它不起作用

vector <- c("a", "b", "c") 

for (i in vector){

  df <- get(i)

  assign(i, mutate(location = paste(i)), envir = .GlobalEnv)
}

2 个答案:

答案 0 :(得分:0)

最好在列表中使用它们。将ls与您的数据帧拥有的pattern一起收集所有数据帧,然后使用mget获取实际数据帧,然后使用cbind

names_df <- ls(pattern = "dataframe")
Map(cbind, mget(names_df), variable = names_df)

使用可复制的数据

dataframe_a <- data.frame(a = 1:5, b = 6:10)
dataframe_b <- data.frame(a = 1:5, b = 6:10)
dataframe_c <- data.frame(a = 1:5, b = 6:10)

names_df <- ls(pattern = "dataframe")
df1 <- Map(cbind, mget(names_df), variable = names_df)
df1

#$dataframe_a
#  a  b    variable
#1 1  6 dataframe_a
#2 2  7 dataframe_a
#3 3  8 dataframe_a
#4 4  9 dataframe_a
#5 5 10 dataframe_a

#$dataframe_b
#  a  b    variable
#1 1  6 dataframe_b
#2 2  7 dataframe_b
#3 3  8 dataframe_b
#4 4  9 dataframe_b
#5 5 10 dataframe_b

#$dataframe_c
#  a  b    variable
#1 1  6 dataframe_c
#2 2  7 dataframe_c
#3 3  8 dataframe_c
#4 4  9 dataframe_c
#5 5 10 dataframe_c

现在,您可以通过df1[["dataframe_a"]]df1[["dataframe_b"]]等访问单个数据帧。

答案 1 :(得分:0)

我们可以使用imap

library(tidyverse)
imap(mget(names_df), ~ .x %>%
            mutate(variable = .y))
#$dataframe_a
#  a  b    variable
#1 1  6 dataframe_a
#2 2  7 dataframe_a
#3 3  8 dataframe_a
#4 4  9 dataframe_a
#5 5 10 dataframe_a

#$dataframe_b
#  a  b    variable
#1 1  6 dataframe_b
#2 2  7 dataframe_b
#3 3  8 dataframe_b
#4 4  9 dataframe_b
#5 5 10 dataframe_b

#$dataframe_c
#  a  b    variable
#1 1  6 dataframe_c
#2 2  7 dataframe_c
#3 3  8 dataframe_c
#4 4  9 dataframe_c
#5 5 10 dataframe_c

数据

dataframe_a <- data.frame(a = 1:5, b = 6:10)
dataframe_b <- data.frame(a = 1:5, b = 6:10)
dataframe_c <- data.frame(a = 1:5, b = 6:10)

names_df <- ls(pattern = "dataframe")