简体   繁体   English

将文本附加到数据框中的列的最佳方法是什么?

[英]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.

相关问题 有没有一种快速的方法将 append 数据帧的所有列转换为单列? - Is there a fast way to append all columns of a data frame into a single column? 检查列是否是R中的嵌套数据框的最佳方法是什么? - What would be the best way to check if a column is a nested data frame in R? 更改R中数据框列类别的最佳方法 - Best way to change class of column of data frame in R 有没有办法自动将彼此下方的 append 数据框列合并为大型数据框列表中的一列? - Is there a way to automatically append data frame columns below each other into one column within large list of data frames? 将列表元素追加到数据框列 - Append list elements to data frame column Append 一个字符到数据帧的列中的特定位置 - Append a character to a specific location in a column in a data frame 使用列名检索 data.frame 列的最佳方法是什么? - What is the best way to retrieve a column of a data.frame with its column name? 将自定义 function 应用于现有列以在 R 的数据框中创建新列的最佳方法 - Best way to apply a custom function to existing column to create a new column in data frame in R 从数据框中获取特定列中具有最小值的行的最佳方法是什么? - What's the best way of getting rows with minimum value in specific column from data frame? 在函数参数中顺序更改的情况下,将函数应用于数据框中的列的最佳方法是什么? - What is the best way to apply a function to a column in a data frame with sequential changes in the function argument?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM