简体   繁体   English

在r中连接两个字符串变量

[英]Concatenating two string variables in r

I've seen plenty of discussion on using paste and paste0 to concatenate two strings in r. 我已经看到很多关于使用paste和paste0来连接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. 我希望将year变量与period变量结合起来,在名为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="")

This is not giving me the expected single variable taking on values "1983M01"... as expected. 这并没有像我们预期的那样给我预期的值变量“1983M01”。 Any thoughts would be greatly appreciated. 任何想法将不胜感激。

Steve 史蒂夫

I encountered the problem mentioned above: I wanted to concatenate "year" (numeric) with a string variable. 我遇到了上面提到的问题:我想将“year”(数字)与字符串变量连接起来。 As a solution, I used "as.character" instead of "toString" and then concatenated the variables using "paste0". 作为解决方案,我使用“as.character”而不是“toString”,然后使用“paste0”连接变量。 This worked for me. 这对我有用。 For example, 例如,

df$c<-paste0(as.character(df$a)," ", as.character(df$b))

I know this is an old post. 我知道这是一个老帖子。 Hoping this helps some other users in a similar situation. 希望这能帮助处于类似情况的其他用户。

Following works: 以下作品:

> 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) binds entire column in one string: toString(ddf $ year)将整个列绑定在一个字符串中:

> 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM