How to include columns in a data.frame?

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) ?

    
asked by anonymous 14.09.2014 / 17:02

3 answers

5

In addition to:

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)

Likewise, you can remove it with:

df$z <- NULL

And it works in all other ways:

df["z"] <- NULL
df[["z"]] <- NULL
df[,"z"] <- NULL
    
14.09.2014 / 18:21
6

Perhaps the simplest way is:

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

A form that is not very well known, but it is interesting to know that it exists, it is using the within() function. Creating a w = c(3,4) vector 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
    
14.09.2014 / 17:05
4

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
    
14.09.2014 / 17:19