![](/img/trans.png)
[英]How do I take a random of sentence in R and count the number of characters per word and sorts the text according to those numbers from words
[英]How do I take specific numbers from a column in R?
我有一個 df 看起來像這樣:
columnA B100 Score Score2
G01440100208022 10010208022 35 2
G01330100208023 10010208023 61 4
G01090100208024 10010208024 48 2
G01007300129114 10730129114 13 1
G62117300129121 10730129121 74 6
G72007300129122 10730129122 63 4
如果columnA
以G0
開頭,我想提取G0
之后的前 4 個數字。 例如,對於前三行,這將是1440,1330,1090
。
如果列以 G(number) 開頭,例如最后一行 (G7)。 我想提取 G 之后的前 5 個數字。例如,這將是62117, 72007
。
有誰知道我如何輕松做到這一點? 理想情況下,最終的 df 看起來像:
columnA B100 Score Score2 New
G01440100208022 10010208022 35 2 1440
G01330100208023 10010208023 61 4 1330
G01090100208024 10010208024 48 2 1090
G01007300129114 10730129114 13 1 1007
G62117300129121 10730129121 74 6 62117
G72007300129122 10730129122 63 4 72007
對於多個條件,一個選項可以是case_when
(不過,在這種情況下,還有其他更簡單的選項)
library(stringr)
library(dplyr)
df1 %>%
mutate(New = case_when(str_detect(columnA, "^G0") ~
str_sub(columnA, 3, 6), TRUE ~ str_sub(columnA,2, 6)))
# columnA B100 Score Score2 New
#1 G01440100208022 10010208022 35 2 1440
#2 G01330100208023 10010208023 61 4 1330
#3 G01090100208024 10010208024 48 2 1090
#4 G01007300129114 10730129114 13 1 1007
#5 G62117300129121 10730129121 74 6 62117
#6 G72007300129122 10730129122 63 4 72007
或者更簡單的選擇是捕獲 'G' 后的 5 位數字,然后轉換為numeric
這樣開頭的 0 將被刪除
df1 %>%
mutate(New = as.integer( sub("^G(\\d{5}).*", "\\1", columnA)))
# columnA B100 Score Score2 New
#1 G01440100208022 10010208022 35 2 1440
#2 G01330100208023 10010208023 61 4 1330
#3 G01090100208024 10010208024 48 2 1090
#4 G01007300129114 10730129114 13 1 1007
#5 G62117300129121 10730129121 74 6 62117
#6 G72007300129122 10730129122 63 4 72007
或者簡單地使用base R
as.integer( sub("^G(\\d{5}).*", "\\1", df1$columnA))
#[1] 1440 1330 1090 1007 62117 72007
或者用substr
as.integer(substr(df1$columnA, 2, 6))
df1 <- structure(list(columnA = c("G01440100208022", "G01330100208023",
"G01090100208024", "G01007300129114", "G62117300129121", "G72007300129122"
), B100 = c(10010208022, 10010208023, 10010208024, 10730129114,
10730129121, 10730129122), Score = c(35L, 61L, 48L, 13L, 74L,
63L), Score2 = c(2L, 4L, 2L, 1L, 6L, 4L)), class = "data.frame",
row.names = c(NA,
-6L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.