str1 <- c("youaremyfriend","youarethebest")
str2 <- c("ABCDEFGHIJKLMN","thisismydata","thereisabird")
df <-c(str1,str2)
#the ideal research
"youar" "youa" "ABCDE" "this" "ther"
您好,我想从df的所有元素中提取字符串的前三分之一。例如,“youaremyfriend”的长度为14,因此结果应为“youar”。我怎样才能做到这一点?谢谢:))
答案 0 :(得分:2)
如果你有一个字符串,你可以使用内置函数nchar
和substring
(不需要库)
str1 = "youaremyfriend"
str1_length = nchar(str1)
substring_wanted = substr(str1, 1, round(str1_length/3)
"youar"
答案 1 :(得分:1)
使用stringr
可以这样做:
library(stringr)
str1 <- c("youaremyfriend","youarethebest")
str2 <- c("ABCDEFGHIJKLMN","thisismydata","thereisabird")
string <- c(str1, str2)
str_sub(string, start = 1, end = round(str_length(string)/3))
# [1] "youar" "youa" "ABCDE" "this" "ther"
答案 2 :(得分:0)
基础R中的另一种解决方案:
str1 <- c("youaremyfriend", "youarethebest", "BBBAAAKKK")
str2 <- c("ABCDEFGHIJKLMN", "thisismydata", "thereisabird")
df <- data.frame(str1, str2)
c(apply(df, c(1, 2), function(s) {
strtrim(s, width = nchar(s)/3)
}))
您的第一列缺少一个条目,因此我添加了一个来构建数据框。