R:如何从一串单词中显示前n个字符

时间:2015-10-18 14:36:34

标签: r string substr strsplit

我有以下字符串:

 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" 

有没有办法可以改变我的代码来打印上面的内容?

谢谢大家!

3 个答案:

答案 0 :(得分:4)

转动你的代码,你得到了你想要的东西。

  def create
    # todo this is not storing full_name
    fn = params[:first_name].to_s.strip
    ln = params[:last_name].to_s.strip
    @customer = Customer.new(customer_params)
    if @customer.save
      # construct full name & save (again) before redirecting
      @customer[:full_name] = fn + ' ' + ln
      @customer.save
      redirect_to customer_index_path
    else
      render 'new'  # user entered values available in @customer
    end
  end

答案 1 :(得分:3)

其他答案并没有像您在示例中那样消除空格,因此我将添加:

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

答案 2 :(得分:2)

您获得"c(\"F\", \"o\""的原因是strsplit输出为list。我们可以通过提取第一个list元素将vector转换为list[[1]]。使用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"