首页 > 解决方案 > 在 R 中创建一个长字符串向量

问题描述

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

例子:

DUAN W  
GU B    
WHINSTON AB etc.

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

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

标签: rvectorpaste

解决方案


假设您的工作簿是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    

推荐阅读