[英]how to grab specific columns from multiple data.frame and save it as a new data.frame in R?
I have the following example data.frame
which contains multiple variables (ie, A,B,C).我有以下示例data.frame
,其中包含多个变量(即 A、B、C)。
set.seed(123)
D1 <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2001-01-10"), by="day"),
A = runif(10,1,5),
B = runif(10,3,6),
C = runif(10,2,5))
D2 <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2001-01-10"), by="day"),
A = runif(10,1,5),
B = runif(10,3,6),
C = runif(10,2,5))
D3 <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2001-01-10"), by="day"),
A = runif(10,1,5),
B = runif(10,3,6),
C = runif(10,2,5))
Target I want to grab each variables from all the data.frame
and save it as a new data.frame
with the name set as Variable
and column names set as data.frame+variable
like below目标我想从所有data.frame
中获取每个变量并将其保存为一个新的data.frame
,名称设置为Variable
,列名设置为data.frame+variable
,如下所示
A <- data.frame(Date, D1A,D2A,D3A)
B <- data.frame(Date,D1B,D2B,D3B)
C <- data.frame(Date,D1C,D2C,D3C)
I would appreciate any help here.我会很感激这里的任何帮助。
We get the datasets in a list
(without the first column 'Date'), transpose
, then loop over the list
with map
, bind the 'Date' column in each of those datasets (it is better to keep it as a list
, but if needed use list2env
to create the objects in the global env)我们将数据集放在一个list
(没有第一列“日期”), transpose
,然后使用map
list
,在每个数据集中绑定“日期”列(最好将其保留为list
,但是如果需要,使用list2env
在全局环境中创建对象)
library(dplyr)
library(purrr)
list(D1 = D1[-1], D2 = D2[-1], D3 = D3[-1]) %>%
transpose %>%
map(~ bind_cols(D1['Date'], .)) %>%
list2env(.GlobalEnv)
-check the objects A, B, C created - 检查创建的对象 A、B、C
head(A, 2)
# Date D1 D2 D3
#1 2001-01-01 2.150310 4.852097 3.660461
#2 2001-01-02 4.153221 4.609196 1.379363
head(B, 2)
# Date D1 D2 D3
#1 2001-01-01 5.870500 3.428400 5.263425
#2 2001-01-02 4.360002 4.243639 4.887663
head(C, 2)
# Date D1 D2 D3
#1 2001-01-01 4.668618 2.137494 2.730858
#2 2001-01-02 4.078410 3.326600 4.004167
Here is a base R option这是一个基本的 R 选项
lst <- mget(ls(pattern = "^D\\d+"))
list2env(
sapply(
names(lst[[1]])[-1],
function(x) {
cbind(
lst[[1]]["Date"],
list2DF(lapply(lst, `[[`, x))
)
},
USE.NAMES = TRUE,
simplify = FALSE
),
envir = .GlobalEnv
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.