r - 使用 str_detect() 从列中提取信息,然后创建一个新列
问题描述
我正在使用一个 data.frame,其中包含一个其值命名如下的列:D1_open、D9_shurb、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"))
解决方案
这是使用separate
from的一种方法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
推荐阅读
- c# - 在 Azure Durable Functions 中,如何正确确定大量并行活动的进程?
- python - 如何将深度网络分成两个独立的网络?
- swift - 使用 SDWebImage 加载 GIF 占用的内存比预期的要多得多
- javascript - 如何在 react-redux 应用程序中设置嵌套路由?
- javascript - 同时动画导航菜单下拉菜单
- c# - 第一个失败的权限类型是:- 错误
- java - 无法使用 java 在 xlsx 文件中写入数据?
- wordpress - WooCommerce 订阅和 Yith 我的帐户问题
- c# - 如何在一个事务中移动多个 blob?
- javascript - Extendscript 是否能够使用文件对象压缩/解压缩文件?