Hand holding pencil reviewing colorful data charts on desk with laptop.

Learn how to Upload Column If It Does Now not Exist in R

Posted on
banner 336x280

You’ll significance refer to customized serve as so as to add a number of columns to an information body in R if they don’t exist already:

add_cols <- serve as(df, cols) {
  upload <- cols[!cols %in% names(df)]
  if(territory(upload) != 0) df[add] <- NA
  go back(df)
}

Refer to instance displays methods to significance this syntax in follow.

banner 468x60

Instance: Upload Column If It Does Now not Exist in R

Assume we have now refer to information body in R:

#form information body
df <- information.body(workforce=c('A', 'A', 'A', 'A', 'B', 'B', 'B'),
                 place=c('Gu', 'Fo', 'Fo', 'Fo', 'Gu', 'Gu', 'Fo'),
                 issues=c(18, 22, 19, 14, 14, 11, 20))

#view information body
df

  workforce place issues
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

Assume we wish to upload refer to columns to the knowledge body if they don’t exist already:

We will significance a customized serve as referred to as add_cols to take action:

#outline customized serve as so as to add columns to information body if they don't exist
add_cols <- serve as(df, cols) {
  upload <- cols[!cols %in% names(df)]
  if(territory(upload) !=0 ) df[add] <- NA
  go back(df)
}

#upload 3 columns in the event that they don't exist already
df <- add_cols(df, c('issues', 'assists', 'rebounds'))

#view up to date information body
df

  workforce place issues 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

Understand that the assists and rebounds columns had been added to the knowledge body moment the issues column used to be no longer because it already existed.

Additionally word that R merely fills in each and every worth within the pristine columns with NA values.

Extra Sources

Refer to tutorials give an explanation for methods to carry out alternative habitual duties in R:

Learn how to Upload Column to Knowledge Body In keeping with Alternative Columns in R
Learn how to Upload an Index (numeric ID) Column to a Knowledge Body in R
Learn how to Upload an Unoccupied Column to a Knowledge Body in R

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *