這是一個小函數,它將字符串取消列表,將前十個單詞分組,然後將它們粘貼在一起。
string_fun <- function(x) {
ul = unlist(strsplit(x, split = "\\s+"))[1:10]
paste(ul,collapse=" ")
}
string_fun(x)
df <- read.table(text = "Keyword,City(Column Header)
The length of the string should not be more than 10 is or are in,New York
The Keyword should be of specific length is or are in,Los Angeles
This is an experimental basis program string is or are in,Seattle
Please help me with getting only the first ten words is or are in,Boston", sep = ",", header = TRUE)
df <- as.data.frame(df)
使用申請(該功能未在第二列做任何事情)
df$Keyword <- apply(df[,1:2], 1, string_fun)
編輯 這大概是使用功能的更一般的方式。
df[,1] <- as.character(df[,1])
df$Keyword <- unlist(lapply(df[,1], string_fun))
print(df)
# Keyword City.Column.Header.
# 1 The length of the string should not be more than New York
# 2 The Keyword should be of specific length is or are Los Angeles
# 3 This is an experimental basis program string is or Seattle
# 4 Please help me with getting only the first ten Boston
函數的第二行可以簡化爲:'paste(ul,collapse =「」)' – thelatemail
什麼是library for unlist in r?@Martin Bel – user3188390
'''unlist()'''是在base中,不需要加載它!閱讀文檔'''?unlist''' – marbel