首页 > 解决方案 > 使用 str_detect() 从列中提取信息,然后创建一个新列

问题描述

我正在使用一个 data.frame,其中包含一个其值命名如下的列:D1_open、D9_sh​​urb、D10_open 等

在此处输入图像描述

我想创建一个新列,其值只是“open”或“shurb”。也就是说,我想从“ID_SubPlot”中提取“open”和“shrub”这两个词,并将它们放在一个新列中。我相信 str_detect() 可能有用,但我不知道如何。

示例数据:

test <- structure(list(ID_Plant = c(243, 370, 789, 143, 559, 588, 746, 
618, 910, 898), ID_SubPlot = c("D1_open", "D9_shrub", "D8_open", 
"E4_shrub", "U5_shrub", "U10_open", "S10_shrub", "U10_shrub", 
"S9_shrub", "S9_shrub")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

标签: rdataframetidyversestringr

解决方案


这是使用separatefrom的一种方法tidyr

library(tidyr)

separate(test, ID_SubPlot, into = c("Code", "NewCol"), sep = "_")

输出

   ID_Plant Code NewCol
1       243   D1   open
2       370   D9  shrub
3       789   D8   open
4       143   E4  shrub
5       559   U5  shrub
6       588  U10   open
7       746  S10  shrub
8       618  U10  shrub
9       910   S9  shrub
10      898   S9  shrub

推荐阅读