![](/img/trans.png)
[英]How can I use regular expression to select the columns of data frame in r?
[英]How can I search for a regular expression in each box of data frame column, and then return just the match instead of the whole field in R?
我有以下數據框:
df <- data.frame(a=c("23034185- Breast Cancer","24586730- Glioblastoma"), b=c(25, 47))
我想搜索 a 列以查看該框是否包含數字,如果是,則僅返回數字而不是整個字段。 所以 output 應該是“23034185”、“24586730”而不是包含整個字段。
請幫忙,謝謝。
一個可能的解決方案:
library(tidyverse)
df <- data.frame(a=c("23034185- Breast Cancer","24586730- Glioblastoma"), b=c(25, 47))
df %>%
mutate(number = str_extract(a, "^\\d+"))
#> a b number
#> 1 23034185- Breast Cancer 25 23034185
#> 2 24586730- Glioblastoma 47 24586730
我們可以使用來自基礎 R 的gsub
。 模式[^0-9]
表示“在df$a
中查找不是數字的字符並將它們替換為空字符”。
df$c <- gsub('[^0-9]', '', df$a)
> df
a b c
1 23034185- Breast Cancer 25 23034185
2 24586730- Glioblastoma 47 24586730
df$c
列實際上不包含數字,而是字符串。
> str(df$c)
chr [1:2] "23034185" "24586730"
如果您希望使用這些數字執行任何計算,您可以使用as.numeric()
直接將它們轉換為數字。
df$c <- as.numeric(gsub('[^0-9]', '', df$a))
> str(df$c)
num [1:2] 23034185 24586730
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.