简体   繁体   中英

Concatenating two string variables in 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="")

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

Steve

I encountered the problem mentioned above: I wanted to concatenate "year" (numeric) with a string variable. As a solution, I used "as.character" instead of "toString" and then concatenated the variables using "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)
[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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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