问题
This should be simple, but I am struggling with it.
I want to combine two columns in a single dataframe into one. I have separate columns for custemer ID (20227) and year (2009). I want to create a new column that has both (2009_20227).
回答1:
Some alternative way with function unite
in tidyr
:
library(tidyr)
df = data.frame(year=2009:2013, customerID=20227:20231) # using akrun's data
unite(df, newcol, c(year, customerID), remove=FALSE)
# newcol year customerID
#1 2009_20227 2009 20227
#2 2010_20228 2010 20228
#3 2011_20229 2011 20229
#4 2012_20230 2012 20230
#5 2013_20231 2013 20231
回答2:
You could use paste
transform(dat, newcol=paste(year, customerID, sep="_"))
Or use interaction
dat$newcol <- as.character(interaction(dat,sep="_"))
data
dat <- data.frame(year=2009:2013, customerID=20227:20231)
回答3:
Another alternative (using the example of @akrun):
dat <- data.frame(year=2009:2013, customerID=20227:20231)
dat$newcol <- paste(dat$year, dat$customerID, sep="_")
来源:https://stackoverflow.com/questions/27906021/merge-2-columns-into-one-in-dataframe