試試這個:
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()
以上的回報代碼:
Observations: 0
Variables: 7
$ Tom <chr>
$ Dick <chr>
$ Harry <chr>
$ John <chr>
$ Paul <chr>
$ George <chr>
$ Ringo <chr>
你可以把它變成一個功能:
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)
}
,然後執行此:
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>
您首先使用什麼函數來讀取您的csv(myNames)? –
一個可重複的例子會很有幫助,但是:'colnames(df)< - as.character(unlist(myNames [1,]))'?另請參閱'?scan' –