Reputation: 1814
I want to take a row and use it to set the colnames example below
df1a = data.frame(Customer = c("A", "a",1:8), Product = c("B", "b",11:18))
colnames(df1a)<-df1a[2,]
Expected output
a b
1 A B
2 a b
3 1 11
4 2 12
5 3 13
6 4 14
7 5 15
8 6 16
9 7 17
10 8 18
I think the problem is that df1a[2,]
is a data frame
Upvotes: 1
Views: 55
Reputation: 886938
Here the columns are factor
class as by default stringsAsFactors = TRUE
in the data.frame
call. So, the values that got changed are the integer storage values of the factor
rather than the acutal values
df1a <- data.frame(Customer = c("A", "a",1:8),
Product = c("B", "b",11:18), stringsAsFactors = FALSE)
and then do the assignment
names(df1a) <- unlist(df1a[2,])
Or as @Ryan mentioned, unlist
is not needed
names(df1a) <- df1a[2,]
Upvotes: 4
Reputation: 23788
You can change the names without generating a new data.frame:
names(df1a) <- lapply(df1a[2,], as.character)
Upvotes: 2