在数据框中将2列合并为一列 [英] Merge 2 columns into one in dataframe

查看:55
本文介绍了在数据框中将2列合并为一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很简单,但是我正在为此而苦苦挣扎.

This should be simple, but I am struggling with it.

我想将一个数据帧中的两列合并为一个.我为客户ID(20227)和年份(2009)有单独的列.我想创建一个同时包含(2009_20227)的新列.

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

推荐答案

tidyr 中使用功能 unite 的某些替代方法:

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列合并为一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆