简体   繁体   中英

How to extract all words after the nth word from string in R?

The first column in my data.frame consists of strings, and the second column are unique keys.

I want to extract all words after the nth word from each string, and if the string has <= n words, extract the entire string.

I have over 10k rows in my data.frame and was wondering if there is a quick way of doing this other than using for loops?

Thanks.

How about the following:

# Generate some sample data
library(tidyverse)
df <- data.frame(
    one = c("Entries from row one", "Entries from row two", "Entries from row three"),
    two = runif(3))


# Define function to extract all words after the n=1 word 
# (or return the full string if n > # of words in string)
crop_string <- function(ss, n) {
    lapply(strsplit(as.character(ss), "\\s"), function(v)
        if (length(v) > n) paste(v[(n + 1):length(v)], collapse = " ")
        else paste(v, collapse = " "))
}

# Let's crop strings from column one by removing the first 3 words (n = 3)
n <- 3;
df %>%
    mutate(words_after_n = crop_string(one, n))
#                     one       two words_after_n
#1   Entries from row one 0.5120053           one
#2   Entries from row two 0.1873522           two
#3 Entries from row three 0.0725107         three


# If n > # of words, return the full string
n <- 10;
df %>%
    mutate(words_after_n = crop_string(one, n))
#                     one       two          words_after_n
#1   Entries from row one 0.9363278   Entries from row one
#2   Entries from row two 0.3024628   Entries from row two
#3 Entries from row three 0.6666226 Entries from row three

here I use nchar(), so make your data has transformed to the character.

as.character(YOUR_DATA)
as.character(sapply(YOUR_DATA,function(x,y){
if(nchar(x)>=y){
substr(x,y,nchar(x))  
}
else{x}
},y= nth_data_you_want))

asumme the data is like:
"gene@seq"
"Cblb@TAGTCCCGAAGGCATCCCGA"
"Fbxo27@CCCACGTGTTCTCCGGCATC"

"Fbxo11@GGAATATACGTCCACGAGAA"

"Pwp1@GCCCGACCCAGGCACCGCCT"

I use 10 as nth data, the result is:

"gene@seq"
"CCCGAAGGCATCCCGA"
"CACGTGTTCTCCGGCATC"

"AATATACGTCCACGAGAA"

"GACCCAGGCACCGCCT"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM