Reputation: 72919
Is there any option in base R, how to set the row and columns names, i. e. dimension names while creating an object in base R?
Example:
Assuming we have a data frame 'dfe'.
set.seed(8803)
dfe <- data.frame(V1=sample(1:10, 3),
V2=sample(1:10, 3),
V3=sample(1:10, 3),
V4=sample(1:10, 3))
dfe
# V1 V2 V3 V4
# 1 3 7 1 6
# 2 9 4 6 5
# 3 5 2 8 9
We can set column names with names(dfe) <- month.abb[1:4]
or (for data frames) colnames(dfe) <- month.abb[1:4]
. Accordingly for the row names rownames(dfe) <- LETTERS[1:3]
.
We also can do both in one process with dimnames()
. Together with creating the data frame there are two steps though.
dfe <- data.frame(.)
dimnames(dfe) <- list(LETTERS[1:3], month.abb[1:4])
dfe
# Jan Feb Mar Apr
# A 3 3 2 1
# B 9 4 6 9
# C 10 1 5 5
With setNames()
we can give column names while creating the data frame.
dfe <- setNames(data.frame(V1=sample(1:10, 3),
V2=sample(1:10, 3),
V3=sample(1:10, 3),
V4=sample(1:10, 3)), month.abb[1:4])
names(dfe)
# [1] "Jan" "Feb" "Mar" "Apr"
Have I missed something for the row names, even better dimension names in base R that sets these while creating an object? I couldn't find something like setRowNames()
or setDimNames()
. How do you do this?
Note: The solution should be rather be a general solution for objects than just fitting for creating data frames or matrices.
Upvotes: 1
Views: 816
Reputation: 269654
This works for both data frames and matrices. Here BOD
is a data frame that comes with R but this code also works if we replace BOD
with as.matrix(BOD)
"rownames<-"(BOD, letters[1:6])
Upvotes: 3