Create a list of column names

Hi! Welcome!

You seem to be doing a very common thing, which is to approach a problem in a new language the way you would solve it in the language you already know. This is an understandable strategy, but it can lead you to do things in an unnecessarily roundabout fashion.

Here's a typical way to approach this task in R:

# This line is only necessary to set up the example CSV!
write.csv(head(iris), "iris.csv", row.names = FALSE)

# Read in a CSV
iris_data <- read.csv("iris.csv", header = TRUE, stringsAsFactors = FALSE)

iris_data
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa

# Perform manipulations on column names. Here, we'll convert 
# column names to lowercase and replace periods with underscores
names(iris_data) <- gsub("\\.", "_", tolower(names(iris_data)))

# Write a CSV with updated column names
write.csv(iris_data, "iris2.csv", row.names = FALSE)

Created on 2018-08-13 by the reprex package (v0.2.0).

Here's what iris2.csv looks like:

"sepal_length","sepal_width","petal_length","petal_width","species"
5.1,3.5,1.4,0.2,"setosa"
4.9,3,1.4,0.2,"setosa"
4.7,3.2,1.3,0.2,"setosa"
4.6,3.1,1.5,0.2,"setosa"
5,3.6,1.4,0.2,"setosa"
5.4,3.9,1.7,0.4,"setosa"

I'm afraid I don't follow this part. I don't see any zero-length strings getting added to your CSV. Instead, your CSV output has row names, but that's just because write.csv() creates row names by default unless you set the row.names parameter to FALSE.

5 Likes