试试这个:
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' –