Concatenating two string variables in r

旧巷老猫 提交于 2019-12-10 05:32:20

问题


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


回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/26321702/concatenating-two-string-variables-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!