0

I am new to R and want to add a column to an existing data frame with values. For example, say this is my current table

Column 1  |  Column 2  | Column 3
---------------------------------
Dog       |    Hound   |   Black
Doggo     |    Lab     |   Brown

I want to add another column such that the result would be this:

Column 1  |  Column 2  | Column 3 |  Column 4
---------------------------------------------
Dog       |    Hound   |   Black  |  Male
Dog       |    Hound   |   Black  |  Female
Doggo     |    Lab     |   Brown  |  Male
Doggo     |    Lab     |   Brown  |  Female

So it'd be almost like adding another dimension, but with a column. Any help would be appreciated!

Edit: found solution here https://stackoverflow.com/a/21911221/9882844

Second edit: Solution below in comment below is better actually

Santi
  • 381
  • 1
  • 3
  • 7

1 Answers1

0

You can use merge with parameter all=TRUE:

df2 <- data.frame(Column4 = c("Male","Female"),stringsAsFactors = FALSE)

merge(df,df2,all = T)
#   Column1 Column2 Column3 Column4
# 1     Dog   Hound   Black    Male
# 2   Doggo     Lab   Brown    Male
# 3     Dog   Hound   Black  Female
# 4   Doggo     Lab   Brown  Female

You can also use crossing from tidyr library, which returns the order of your expected output:

tidyr::crossing(df,df2)
#   Column1 Column2 Column3 Column4
# 1     Dog   Hound   Black    Male
# 2     Dog   Hound   Black  Female
# 3   Doggo     Lab   Brown    Male
# 4   Doggo     Lab   Brown  Female

data

df <- read.table(text="Column1    Column2   Column3
Dog           Hound      Black
Doggo         Lab        Brown",h=T,strin=F)
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167