Merge 2 columns into one in dataframe [closed]

放肆的年华 提交于 2021-02-04 16:55:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!