在r中连接两个字符串变量 [英] Concatenating two string variables in r

查看:1961
本文介绍了在r中连接两个字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多关于使用粘贴和paste0连接r中的两个字符串的讨论。但是,这似乎并不适用于两个字符串变量。我有一个数据框,如下所示。

I've seen plenty of discussion on using paste and paste0 to concatenate two strings in r. However, this does not appear to be working for two string variables. I have a data frame that looks like the following.

    series_id   year    period  value   footnote_codes
1   LASBS260000000000003            1983    M01 15.1              
2   LASBS260000000000003            1983    M02 15.0              
3   LASBS260000000000003            1983    M03 14.8              
4   LASBS260000000000003            1983    M04 14.6

我想结合年变量到期间变量,在数据框中产生一个新的变量,称为观察。数据框被称为数据,我根据类似查询的研究尝试了以下粘贴命令。

I wish to combine the year variable to the period variable to generate a new variable in the data frame called observation. The data frame is called data and I tried the following paste command based on research of similar inquiries.

data$obs<-paste0(toString(data$year),toString(data$period))
data$obs<-paste(toString(data$year),toString(data$period),sep="")

这不是给我预期的单个变量承担值1983M01...如预期。任何想法都将不胜感激。

This is not giving me the expected single variable taking on values "1983M01"... as expected. Any thoughts would be greatly appreciated.

Steve

推荐答案

> apply(ddf,1 ,function(x) paste0(toString(x[2]), toString(x[3])))
[1] "1983M01" "1983M02" "1983M03" "1983M04"
> 
> apply(ddf,1 ,function(x) paste(toString(x[2]), toString(x[3])))
[1] "1983 M01" "1983 M02" "1983 M03" "1983 M04"

toString(ddf $ year)绑定一个字符串中的整个列:

toString(ddf$year) binds entire column in one string:

> toString(ddf$year)
[1] "1983, 1983, 1983, 1983"
> 
> toString(ddf$period)
[1] "M01, M02, M03, M04"
> 
> paste(toString(ddf$year), toString(ddf$period))
[1] "1983, 1983, 1983, 1983 M01, M02, M03, M04"

这篇关于在r中连接两个字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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