Concatenating two string variables in r

人走茶凉 提交于 2019-12-05 11:18:49

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"

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.

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