简体   繁体   中英

How to save an R data.frame as CSV with no spaces?

I have the following data.frame that I am saving as CSV file. When the data.frame is saved as CSV I see one point space after the Text component (see the image). How to avoid the space creation while saving data.frame as CSV ? Thank you

library(lubridate)
library(tidyverse)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2001-12-31"), by = "days"), Flow = runif(365, 1, 5)) %>% 
      mutate(Year = year(Date), Month = month(Date), Day = day(Date), JDay = yday(Date), Text = rep("FLOW_OUT_",365)) %>% 
      mutate(Format = paste(Text,JDay,"_",Year)) %>% 
      select(8) %>% 
      write.csv(file = "Format.csv")

在此处输入图片说明

We can use paste0 instead of paste to avoid creating the spaces as the default sep option in paste is sep= " "

...
  mutate(Format = paste0(Text,JDay,"_",Year))
...

-full code

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2001-12-31"), 
         by = "days"), Flow = runif(365, 1, 5)) %>% 
      mutate(Year = year(Date), Month = month(Date),
      Day = day(Date), JDay = yday(Date), Text = rep("FLOW_OUT_",365)) %>% 
      mutate(Format = paste0(Text,JDay,"_",Year)) %>% 
      select(8)

Or another option is making use of sep argument in paste

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2001-12-31"), 
             by = "days"), Flow = runif(365, 1, 5)) %>% 
          mutate(Year = year(Date), Month = month(Date),
          Day = day(Date), JDay = yday(Date), Text = rep("FLOW_OUT_",365)) %>% 
          mutate(Format = paste(Text,JDay,"_",Year, sep="")) %>% 
          select(8)

-output

head(DF)
#           Format
#1 FLOW_OUT_1_2001
#2 FLOW_OUT_2_2001
#3 FLOW_OUT_3_2001
#4 FLOW_OUT_4_2001
#5 FLOW_OUT_5_2001
#6 FLOW_OUT_6_2001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM