How to include columns in a data.frame?

Asked

Viewed 16,549 times

3

Consider the following data.frame:

df <- data.frame(x=c("a","b"), y=c(1,2))

How to include a new column, say, z = c(1,2)?

4 answers

8


Beyond the:

df$z <- c(1,2)

Other simple ways to add just one column are:

df["z"] <- c(1,2) df[["z"]] <- c(1,2) df[,"z"] <- c(1,2)

Similarly, you can remove it with:

df$z <- NULL

And it works in every other way:

df["z"] <- NULL
df[["z"]] <- NULL
df[,"z"] <- NULL

7

Maybe the simplest way is:

df$z <- c(1,2)
df
  x y z
1 a 1 1
2 b 2 2

One way that is not very well known, but it is interesting to know that it exists, is by using the function within(). Creating a vector w = c(3,4) as an example:

df <- within(df, w <- c(3,4))
df
  x y z w
1 a 1 1 3
2 b 2 2 4

5

You can also use the Transform function.

df <- transform(df, z=c(1,2),  w=c(3,4))

  x y z w
1 a 1 1 3
2 b 2 2 4

1

The function mutate() of dplyr may also be an option:

library(dplyr)

mutate(df, z=c(1,2))

  x y z
1 a 1 1
2 b 2 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.