我是R的新手,想要使用值向现有数据框添加列。例如,假设这是我当前的表
Column 1 | Column 2 | Column 3
---------------------------------
Dog | Hound | Black
Doggo | Lab | Brown
我想添加另一列,结果如下:
Column 1 | Column 2 | Column 3 | Column 4
---------------------------------------------
Dog | Hound | Black | Male
Dog | Hound | Black | Female
Doggo | Lab | Brown | Male
Doggo | Lab | Brown | Female
所以它几乎就像添加另一个维度,但是有一个列。任何帮助将不胜感激!
修改:在此处找到解决方案https://stackoverflow.com/a/21911221/9882844
第二次修改:以下评论中的解决方案实际上更好
答案 0 :(得分:0)
您可以将merge
与参数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
您还可以使用crossing
库中的tidyr
,它会返回您预期输出的顺序:
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
数据强>
df <- read.table(text="Column1 Column2 Column3
Dog Hound Black
Doggo Lab Brown",h=T,strin=F)