簡體   English   中英

如何創建包含 3 個新列(每列來自不同數據集)的數據集並重命名它們?

[英]How can I create a dataset with 3 new columns (each one from a different dataset) and rename them?

我知道這是一個簡單的問題,但我真的很掙扎,並試圖提高我的代碼效率。 我有 3 個不同的數據集:

    head(Porto_2014)
    + select(points_acc)     
          points_acc
    1          3
    2          6
    3          9
    4         10
    5         11
    6         12

    head(Porto_2015) %>%
    + select(points_acc)
      points_acc
    1          3
    2          4
    3          7
    4         10
    5         13
    6         14

head(Porto_2016) %>%
+ select(points_acc)
  points_acc
1          3
2          6
3          6
4          9
5         10
6         13

我想創建一個新的數據幀points_by_season名為3列Season_XX本賽季的一年。 我必須記得,我希望對用於編碼的行變得非常高效。 先感謝您

一種選擇是通過獲取對象的值(使用mget )將其加載到list ,遍歷列表( imap ), select該列,同時將其重命名,將list名稱中的 'Porto' 替換為 'Season'

library(dplyr)
library(purrr)
library(stringr)
imap_dfc(mget(str_c("Porto_", 2014:2016)), ~ .x %>%
            select(!!str_replace(.y, "Porto", "Season") := points_acc)) 
#   Season_2014 Season_2015 Season_2016
#1           3           3           3
#2           6           4           6
#3           9           7           6
#4          10          10           9
#5          11          13          10
#6          12          14          13

或者在base R

setNames(do.call(cbind, lapply(mget(paste0("Porto_", 2014:2016)),
           `[`, 'points_acc')), paste0("Season_", 2014:2016))

數據

Porto_2014 <- structure(list(points_acc = c(3L, 6L, 9L, 10L, 11L, 12L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))
Porto_2015 <- structure(list(points_acc = c(3L, 4L, 7L, 10L, 13L, 14L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))
Porto_2016 <- structure(list(points_acc = c(3L, 6L, 6L, 9L, 10L, 13L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

您可以使用cbind

如果 Porto_2014、Porto_2015 和 Porto_2016 具有相同的行數:

points_by_season <- cbind(Season_2014=Porto_2014$points_acc
 , Season_2015=Porto_2015$points_acc
 , Season_2016=Porto_2016$points_acc)

如果它們的行數不同:

tt <- seq_len(max(nrow(Porto_2014), nrow(Porto_2015), nrow(Porto_2016)))
points_by_season <- cbind(Season_2014=Porto_2014$points_acc[tt]
 , Season_2015=Porto_2015$points_acc[tt]
 , Season_2016=Porto_2016$points_acc[tt])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM