如何从CSV输出中删除换行符

时间:2019-10-14 14:40:36

标签: sql r

我正在尝试在csv文件中添加新列,以在“说明”列包含文本字符串的情况下在新列中添加“ 1”。看起来代码可以工作,但是write.csv通过在“说明”列中添加换行符来弄乱输出文件

我是R的新手,并尝试了一些方法,包括使用 库(字符串)

data1 = str_replace_all(data1, "[\r\n]" , "")

但是它卡住了!

data = read_excel("database.xlsx")
data1 = sqldf(c("alter table data add newcolumn numeric","select * from data"))
data1 = sqldf(c("update data1 set newcolumn = case when Description LIKE '%pyramidlike%' then 1 else 0
        end", "select * from data1"))
write.csv(data1, "data1.csv")

1 个答案:

答案 0 :(得分:0)

您没有包括示例数据以使其成为可重复的示例。但是,仍然有更简单的方法来实现您想要的工作,我将使用示例数据仓库(iris):

library(tidyverse)

# will use the IRIS dataset instead of your XLSX, adjust as needed.
data(iris)
new_iris <- iris %>% 
  mutate(
    flag = ifelse(Species == "setosa", 1, 0)  # add a new column
  )

为了清楚说明发生了什么,让我们看一下数据帧的结构:

> str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

> str(new_iris)
'data.frame':   150 obs. of  6 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ flag        : num  1 1 1 1 1 1 1 1 1 1 ...

然后只需将数据框写入CSV:

# I am using the tidyverse version of the function
write_csv(
  new_iris,
  path = "/path/to/output.csv"
)

对于这种特殊情况,使用sqldf()来处理数据集没有任何好处。通常,当我直接在数据库中进行更改时,会使用它。

HTH