如何在R中添加不存在的列(附代码示例)

138 阅读1分钟

你可以使用下面的自定义函数在R语言中为一个数据框架添加一个或多个列,如果它们还不存在的话:

add_cols <- function(df, cols) {
  add <- cols[!cols %in% names(df)]
  if(length(add) != 0) df[add] <- NA
  return(df)
}

下面的例子展示了如何在实践中使用这种语法。

例子:在R中不存在的情况下添加列

假设我们在R中拥有以下数据框架:

#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B'),
                 position=c('Gu', 'Fo', 'Fo', 'Fo', 'Gu', 'Gu', 'Fo'),
                 points=c(18, 22, 19, 14, 14, 11, 20))

#view data frame
df

  team position points
1    A       Gu     18
2    A       Fo     22
3    A       Fo     19
4    A       Fo     14
5    B       Gu     14
6    B       Gu     11
7    B       Fo     20

假设我们想在数据框中添加以下列,如果它们还不存在的话:

  • 助攻
  • 篮板

我们可以使用一个名为add_cols的自定义函数来实现这一目的:

#define custom function to add columns to data frame if they do not exist
add_cols <- function(df, cols) {
  add <- cols[!cols %in% names(df)]
  if(length(add) !=0 ) df[add] <- NA
  return(df)
}

#add three columns if they don't already exist
df <- add_cols(df, c('points', 'assists', 'rebounds'))

#view updated data frame
df

  team position points assists rebounds
1    A       Gu     18      NA       NA
2    A       Fo     22      NA       NA
3    A       Fo     19      NA       NA
4    A       Fo     14      NA       NA
5    B       Gu     14      NA       NA
6    B       Gu     11      NA       NA
7    B       Fo     20      NA       NA

注意,助攻篮板这两列被添加到数据框中,而得分这一列则没有,因为它已经存在了。

还要注意的是,R只是在新列中的每个值中填入了NA值。