根据列数在数据框列表中创建新变量

Create new variable in dataframe list based on number of columns

我有一个包含两个数据框的列表,第一个有两列,第二个有三列。

dat.list<-list(dat1=data.frame(col1=c(1,2,3),
                     col2=c(10,20,30)),
     dat2= data.frame(col1=c(5,6,7),
                      col2=c(30,40,50),
                      col3=c(7,8,9)))

# $dat1
 #  col1 col2
# 1    1   10
# 2    2   20
# 3    3   30

# $dat2
 
#   col1 col2 col3
# 1    5   30    7  
# 2    6   40    8  
# 3    7   50    9 

我正在尝试使用 map()mutate()case_when() 在两个数据框中创建一个新列。如果数据框有两列以上,我希望这个新列与 col3 相同,如果它有两列或更少列,则与 col1 相同。我尝试使用以下代码执行此操作:

library(tidyverse)
dat.list %>% map(~ .x %>%
                   mutate(newcol=case_when(ncol(.)>2 ~ col3,
                                           TRUE  ~ col1),
                          ))

然而,这returns出现以下错误:“找不到对象'col3'”。我怎样才能得到想要的输出?以下是我要实现的确切输出。

# $dat1
#   col1 col2 newcol
# 1    1   10      1
# 2    2   20      2
# 3    3   30      3

# $dat2
#   col1 col2 col3 newcol
# 1    5   30    7      7
# 2    6   40    8      8
# 3    7   50    9      9

if/else 可以:

library(dplyr)
library(purrr)

dat.list %>% map(~ .x %>% mutate(newcol= if(ncol(.) > 2) col3 else col1))

#$dat1
#  col1 col2 newcol
#1    1   10      1
#2    2   20      2
#3    3   30      3

#$dat2
#  col1 col2 col3 newcol
#1    5   30    7      7
#2    6   40    8      8
#3    7   50    9      9

基础 R 使用 lapply :

lapply(dat.list, function(x) transform(x, newcol = if(ncol(x) > 2) col3 else col1))