如何将多个字符列组合成 R 数据框中的单个列 [英] How to combine multiple character columns into a single column in an R data frame
本文介绍了如何将多个字符列组合成 R 数据框中的单个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理人口普查数据,我需要将四个字符列合并为一列.
I am working with Census data and I need to combine four character columns into a single column.
示例:
LOGRECNO STATE COUNTY TRACT BLOCK
60 01 001 021100 1053
61 01 001 021100 1054
62 01 001 021100 1055
63 01 001 021100 1056
64 01 001 021100 1057
65 01 001 021100 1058
我想创建一个新列,将 STATE、COUNTY、TRACT 和 BLOCK 的字符串添加到一个字符串中.示例:
I want to create a new column that adds the strings of STATE, COUNTY, TRACT, and BLOCK together into a single string. Example:
LOGRECNO STATE COUNTY TRACT BLOCK BLOCKID
60 01 001 021100 1053 01001021101053
61 01 001 021100 1054 01001021101054
62 01 001 021100 1055 01001021101055
63 01 001 021100 1056 01001021101056
64 01 001 021100 1057 01001021101057
65 01 001 021100 1058 01001021101058
我试过了:
AL_Blocks$BLOCK_ID<- paste(c(AL_Blocks$STATE, AL_Blocks$County, AL_Blocks$TRACT, AL_Blocks$BLOCK), collapse = "")
但是这将所有四列的所有行合并为一个字符串.
But this combines all rows of all four columns into a single string.
推荐答案
试试这个:
AL_Blocks$BLOCK_ID<- with(AL_Blocks, paste0(STATE, COUNTY, TRACT, BLOCK))
县有一个错字……应该是县.此外,您不需要collapse 参数.
there was a typo in County... it should've been COUNTY. Also, you don't need the collapse parameter.
希望能帮到你.
这篇关于如何将多个字符列组合成 R 数据框中的单个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文