[英]Best way to append text to a column in a data frame?
I have a column in my data frame that has date data in it: 我的数据框中有一个列中包含日期数据:
> head(df$postedDate_strip2,n = 20)
[1] NA "November 13, 2014"
[3] "September 27, 2014" "October 8, 2014"
[5] "December 16, 2013" "February 8"
[7] "November 2, 2014" "November 30, 2014"
[9] "February 18" "August 22, 2014"
[11] "October 26, 2014" "January 3, 2014"
[13] "February 3, 2014" "October 15, 2014"
[15] "September 12, 2014" "May 5"
[17] "April 2, 2014" "November 4, 2014"
[19] "January 16, 2014" "September 28, 2014"
All the 2015 data don't have the , 2015
text at the end. 所有2015年的数据最终都没有, 2015
文字。 Is there a recommended way to simply append ", 2015" to entries that don't contain a comma? 是否有建议的方法只是简单地将“,2015”附加到不包含逗号的条目中?
gsub("(^[^,]+$)", "\\1, 2015", x)
#[1] "December 16, 2013" "February 8, 2015" "November 2, 2014"
#[4] NA "February 18, 2015"
Regex makes the task easier. 正则表达式使任务更容易。 The pattern "(^[^,]+$)"
Checks for strings without a comma and replaces it with the same string with the year appended. 模式"(^[^,]+$)"
检查没有逗号的字符串,并用附加年份的相同字符串替换它。 Using the anchors ^
and $
are vital to the search. 使用锚点^
和$
对搜索至关重要。 The first matches the first position in the string, the latter matches the last position. 第一个匹配字符串中的第一个位置,后者匹配最后一个位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.