将一列分类变量按顺序添加到数据框列表中

时间:2018-06-19 01:42:09

标签: r list dataframe

我有多个数据框,我已将其读入一个列表。我想在此列表中的每个数据框中添加特定序列变量序列的新列。

例如,我有以下数据框列表(data_list):

df1
             Slice    Count    
        1    C1       10          
        2    C2       2      
        3    C3       5    
df2
             Slice    Count    
        1    C1       3          
        2    C2       8      
        3    C3       6    
df3
             Slice    Count    
        1    C1       0          
        2    C2       0      
        3    C3       3    

我写了以下脚本:

region_name <- c("North","East","South")
data_list <- Map(cbind, data_list, Region = region_name)

这就是我得到的:

df1
             Slice    Count    Region    
        1    C1       10       North  
        2    C1       2        North
        3    C1       5        North
df2
             Slice    Count    Region    
        1    C1       3        East  
        2    C1       8        East
        3    C1       6        East
df3
             Slice    Count    Region    
        1    C1       0        South  
        2    C1       0        South
        3    C1       3        South

如何让分类变量在每个数据帧中按顺序重复(不按数据帧顺序重复):

df1
             Slice    Count    Region    
        1    C1       10       North  
        2    C1       2        East
        3    C1       5        South
df2
             Slice    Count    Region    
        1    C1       3        North  
        2    C1       8        East
        3    C1       6        South
df3
             Slice    Count    Region    
        1    C1       0        North  
        2    C1       0        East
        3    C1       3        South

2 个答案:

答案 0 :(得分:0)

以下

怎么样?
# Generate some sample data
set.seed(2017);
lst <- lapply(1:3, function(i) data.frame(Slice = c("C1", "C2", "C3"), Count = sample(10, 3)))

# Add column Region for every data.frame in lst
region_name <- c("North","East","South")
lst <- lapply(lst, function(x) {x$Region = region_name; x});
lst;
#[[1]]
#  Slice Count Region
#1    C1    10  North
#2    C2     5   East
#3    C3     4  South
#
#[[2]]
#  Slice Count Region
#1    C1     3  North
#2    C2     7   East
#3    C3     9  South
#
#[[3]]
#  Slice Count Region
#1    C1     1  North
#2    C2     4   East
#3    C3     9  South

答案 1 :(得分:0)

或者我们可以将mapmutate

一起使用
library(tidyverse)
map(data_list, ~ .x %>% 
                     mutate(Region = region_name))