簡體   English   中英

R:如何從一串單詞中顯示前n個字符

[英]R: how to display the first n characters from a string of words

我有以下字符串:

 Getty <- "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all  men are created equal."

我想顯示前10個字符。 所以我開始將字符串拆分為單個字符:

 split <- strsplit(Getty, split="")
 split 

我得到了所有個人角色。 然后我創建前10個字符的子字符串。

 first.10 <- substr(split, start=1, stop=10)
 first.10

這是輸出:

 "c(\"F\", \"o\""

我不明白為什么打印出來? 我以為它會打印出如下內容:

 "F" "o" "u" "r" "s" 

有沒有辦法可以改變我的代碼來打印上面的內容?

謝謝大家!

轉動你的代碼,你得到你想要的。

Getty <- "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all  men are created equal."


first.10 <- substr(Getty, start=1, stop=10)
first.10
"Four score"
split <- strsplit(first.10, split="")
split 
"F" "o" "u" "r" " " "s" "c" "o" "r" "e"

其他答案沒有像你在你的例子中那樣消除空格,所以我將添加:

strsplit(substr(gsub("\\s+", "", Getty), 1, 10), '')[[1]]
#[1] "F" "o" "u" "r" "s" "c" "o" "r" "e" "a"

你得到"c(\\"F\\", \\"o\\""的原因是因為strsplit輸出是一個list 。我們可以通過提取第一個list元素即[[1]]list轉換為vector 。使用head獲取前10個字符。

head(strsplit(Getty, '')[[1]], 10)

更新

如果你只想提取沒有空格的字符,

library(stringr)
head(str_extract_all(Getty, '[^ ]')[[1]],10)
#[1] "F" "o" "u" "r" "s" "c" "o" "r" "e" "a"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM