0
votes

I have a csv file (myNames) with column names. It is 1 x 66. I want to use those names to rename the 66 columns I have in another dataframe. I am trying to use colnames(df)[]<-(myNames) but I get the wrong result. I have tried to do this using as.vector, as.array, as.list, without success.

  1. Is there a more direct way to read a csv file into an array? or
  2. How can I get an array from my dataframe that I can use in colnames()?

Here's myNames:

v1     v2     v3       v4    v5     v6      v7
Tom    Dick   Harry   John   Paul   George  Ringo

I want to make Tom, Dick, Harry my new column names in mydata.

1
What function did you use to read your csv (myNames) in the first place?Adam Quek
a reproducible example would be helpful, but: colnames(df) <- as.character(unlist(myNames[1,])) ? Also,see ?scanBen Bolker

1 Answers

1
votes

Try this:

library(tidyverse)

# Reproducible example
df <- ("Tom    Dick   Harry   John   Paul   George  Ringo")
df <- read.table(text = df)

# Change column names
names(df) <- as.matrix(df[1, ])

# Remove row 1
df <- df[-1, ]

# Convert to a tibble
df %>% 
  as_tibble() %>% 
  mutate_all(parse_guess) %>% 
  glimpse()

The code above returns:

Observations: 0
Variables: 7
$ Tom    <chr> 
$ Dick   <chr> 
$ Harry  <chr> 
$ John   <chr> 
$ Paul   <chr> 
$ George <chr> 
$ Ringo  <chr> 

You could turn this into a function:

rn_to_cn <- function(dataframe){
  x <- length(colnames(dataframe))
  y <- length(unique(matrix(dataframe)))
  if(x > y){
    stop("Can't have duplicate column names.")
  } else {
    message("It worked!")
  }
  names(dataframe) <- as.matrix(dataframe[1, ])
  dataframe <- dataframe[-1, ]
  dataframe %>% 
    as_tibble() %>% 
    mutate_all(parse_guess)
}

And then do this:

rn_to_cn(df)

# A tibble: 0 x 7
# ... with 7 variables: Tom <chr>, Dick <chr>, Harry <chr>, John <chr>,
#   Paul <chr>, George <chr>, Ringo <chr>