1
xcv(123)
wert(232)
t(145)
tyui ier(133)
ytie(435)
...
字符串的長度是動態的,意味着它是隨機的。括號之間的數字是目標字母,需要在同一數據集的新列中存儲的&。如何從字符變量中取出特定字母
以下關鍵詞可以幫助: substr()
strsplit()
我積極地尋找一個答案。您的幫助將深受讚賞。
xcv(123)
wert(232)
t(145)
tyui ier(133)
ytie(435)
...
字符串的長度是動態的,意味着它是隨機的。括號之間的數字是目標字母,需要在同一數據集的新列中存儲的&。如何從字符變量中取出特定字母
以下關鍵詞可以幫助: substr()
strsplit()
我積極地尋找一個答案。您的幫助將深受讚賞。
你的意思是你想從字符串xcv
中提取例如第123個字母?
set.seed(123)
xcv <- paste(sample(letters, 200, replace = TRUE), collapse = "")
n <- 123
您可以提取n
個字母,像這樣:
substr(xcv, n, n)
# [1] "i"
dat = c('xcv(123)' ,'wert(232)', 't(145)', 'tyui ier(133)', 'ytie(435)')
target = gsub(".*\\(|\\).*", "", dat) #captures anything in between '(' and ')'. We use \\(and \\) to denote the brackets since they are special characters.
cbind(dat, target)
dat target
[1,] "xcv(123)" "123"
[2,] "wert(232)" "232"
[3,] "t(145)" "145"
[4,] "tyui ier(133)" "133"
[5,] "ytie(435)" "435"
你可以做'庫(stringr); str_extract(v1,「(?<= \\()[0-9] +(?= \\))」)'或另一個選項是'library(readr); parse_number(v1)' – akrun
在您的最後一個字符串中,有'435',但你的字只有4個字母(假設我正確理解了這一點)。您應該添加您的預期輸出。與第二個一樣 – Sotos