Reputation: 161
I have imported a dataframe from a csv file. The dataframe looks quite ugly. I would like to rename all variables with the values of the the first observation and to remove this first observation. A colleague of mine gave me an idea with this code.
colnames(df) <- lapply(df[1, ], as.character)
df <- df[-1,]
The code above works perfectly but I love dplyr:-) Is there any way to do the same using pipes and dplyr?
PS: Sorry in advance if I say something stupid. I am a beginner in R and this is my very first question in Stack Overflow.
Upvotes: 0
Views: 931
Reputation: 2716
set.seed(1984)
require(dplyr)
## simulating a data frame
df <- data.frame(a = 1:10,
b = sample(LETTERS,10, replace = T),
c = sample(letters,10, replace = T),
stringsAsFactors = F)
head(df)
a b c
# 1 1 P y
# 2 2 A j
# 3 3 P o
# 4 4 W u
# 5 5 U a
# 6 6 E k
df %>%
filter(row.names(.) == 1) %>%
as.character(.) -> names(df)
df
# 1 P y
# 1 1 P y
# 2 2 A j
# 3 3 P o
# 4 4 W u
# 5 5 U a
# 6 6 E k
# 7 7 W o
# 8 8 P h
# 9 9 N b
# 10 10 O f
Upvotes: 1