从数据框列中删除空格并添加路径

时间:2016-01-04 12:36:24

标签: r

我有一个数据框列,其数据如下:

df$names
"stock 1"
"stock stock1 2"
"stock 2"

我想删除每行文本的空格。像这样的结果:

df$names
"stock1"
"stockstock12"
"stock2"

添加文件名的路径,并有一个这样的最终列(所有行的路径都相同)

df$names
"C:/Desktop/stock_files/stock1"
"C:/Desktop/stock_files/stockstock12"
"C:/Desktop/stock_files/stock2"

1 个答案:

答案 0 :(得分:7)

我们可以使用gsub删除空白区域。我们选择一个或多个空格(\\s+)并将其替换为''

 df$names <- gsub('\\s+', '', df$names)
 df$names
 #[1] "stock1"       "stockstock12" "stock2"    

然后,我们使用paste将字符串连接在一起

  path <- "C:/Desktop/stock_files"
  df$names <- paste(path, df$names, sep="/")
  df$names
  #[1] "C:/Desktop/stock_files/stock1"       "C:/Desktop/stock_files/stockstock12"
  #[3] "C:/Desktop/stock_files/stock2"