以下是示例数据

 stfips <- c("39","39","39")
 year <- c("2023", "2023","2023")
 industry_code <- c(112, 113, 114)
 first_quarter_establishments <- c(987,654,321)
 county <- data.frame(stfips, year, industry_code, first_quarter_establishments)

手头的任务是创建一个名为Period的新列,其值为01.01的原因是因为它代表了第一季度.如果第四列的名称中有单词"Second",则句点将为"02",依此类推.以下是我从ChatGPT上得到的信息.错误如下所示.你知道我将如何根据专栏的措辞创建这个时期的专栏吗?

first_columns <- grepl("first", names(county), ignore.case = TRUE)
county$period <- ifelse(first_columns, "01", "") 
  Error in `$<-.data.frame`(`*tmp*`, period, value = c("", "", "", "01")) : 
  replacement has 4 rows, data has 3

期望的最终结果

 stfips     year    industry_code    first_quarter_establishments   period
  39        2023         112                 987                    01
  39        2023         113                 654                    01
  39        2023         114                 321                    01

推荐答案

我肯定有更好的解决方案,但在基数R中,您可以使用matchgsub组合来从数据帧的names中识别季度:

quarters <- c("first" = 1, "second" = 2, 
              "third" = 3, "fourth" = 4)

county$quarter <- quarters[match(gsub("(.+?)(\\_.*)", "\\1", names(county[4])), 
                                 names(quarters))]

输出:

#   stfips year industry_code first_quarter_establishments quarter
# 1     39 2023           112                          987       1
# 2     39 2023           113                          654       1
# 3     39 2023           114                          321       1

如果要将其更改为Second:

second_quarter_establishments <- c(987,654,321)
county <- data.frame(stfips, year, industry_code, second_quarter_establishments)

county$quarter <- quarters[match(gsub("(.+?)(\\_.*)", "\\1", names(county[4])), 
                                 names(quarters))]

#   stfips year industry_code second_quarter_establishments quarter
# 1     39 2023           112                           987       2
# 2     39 2023           113                           654       2
# 3     39 2023           114                           321       2

请注意,如果重命名quarters vector,可以取消gsub,但假设数据框中的名称完全相同:

quarters <- c("first_quarter_establishments" = 1, "second_quarter_establishments" = 2, 
              "third_quarter_establishments" = 3, "fourth_quarter_establishments" = 4)

county$quarter <- quarters[match(names(county[4]), names(quarters))]

R相关问答推荐

提取R中值和列名的所有可能组合

列出用m n个值替换来绘制n个数字的所有方法(i.o.w.:R中大小为n的集合的所有划分为m个不同子集)

更改绘图上的x轴断点,而不影响风险?

pickerInput用于显示一条或多条geom_hline,这些线在图中具有不同 colored颜色

如何在geom_col中反转条

如何写商,水平线,在一个单元格的表在R

展开对数比例绘图的轴(添加填充)

从服务器在Shiny中一起渲染图标和文本

使用R中的dist()迭代ID匹配的欧几里德距离

我们如何在R中透视数据并在之后添加计算

手动指定从相同数据创建的叠加图的 colored颜色

如何在PrePlot()中将多个元素设置为斜体

变长向量的矢量化和

如何调整一个facet_work()面板内的框图和移动标签之间的水平宽度?

使用ggplot2绘制具有边缘分布的坡度图

隐藏基于 case 总数的值

带有Bootswatch Cerulean主题的shiny 仪表板中的浏览&按钮可见性问题

根据向量对列表元素进行排序

带查找数据的FCT_REORDER.帧

移除y轴断开的geom_bar图的外框