在R中创建字符串的长向量

问题描述 投票:-1回答:1

我在电子表格中有一列很长的名称。这些名称本质上是姓氏,与名字/中间名的缩写开头用空格分隔。

示例:

DUAN W  
GU B    
WHINSTON AB etc.

我需要一个像names <- c("DUAN W","GU B","WHINSTON AB")

当然,我可以在电子表格本身中进行所有这些预处理,然后粘贴到R中。但是我想知道是否可以在R中使用paste()完成此操作。由于必须重复执行此操作,因此有没有一种方法可以避免每次都编写电子表格公式?

r vector paste
1个回答
0
投票

假设您的工作簿为NAMES.xlsx

library(tidyverse)
  # Read them in from the Excel file
readxl::read_excel("C:/temp/NAMES.xlsx") %>% 
   # Divide the single column in two.
  separate(NAMES, into = c("LAST.NAME", "FIRST.NAME"), sep = " ", extra = "merge") %>% 
   # First name goes before last name
  select(FIRST.NAME, LAST.NAME)

# A tibble: 6 x 2
  FIRST.NAME LAST.NAME
  <chr>      <chr>    
1 W          DUAN     
2 B          GU       
3 AB         WHINSTON 
4 M          MOUSE    
5 S          MCDUCK   
6 PP         LEPEW    
© www.soinside.com 2019 - 2024. All rights reserved.