Reputation: 763
I have a dataframe in the following manner
name<-c('z','z','z','d','d','d')
area<-c("A","A","B","B","B","C")
df<-data.frame(area,name)
(df.1<-data.frame(summary(df$area)))
where I get the following output
summary.df.area.
A 2
B 3
C 1
As you can see the A,B,C
values have not been assigned to any specific column, how can I assign these values into a column called area ID
so that it looks like
area ID summary.df.area.
A 2
B 3
C 1
Upvotes: 1
Views: 742
Reputation: 9865
One-liner solution
cbind(data.frame("area ID"=rownames(df.1)), df.1)
## area.ID summary.df.area.
## A A 2
## B B 3
## C C 1
Making a function out of it
And generalized to a function:
# function returning the data frame with rownames as first column
# which has the title given in `firstColName`.
rownamesAsColumn <- function(df, firstColName) {
res <- cbind(data.frame(firstCol=rownames(df)), df)
colnames(res) <- c(firstColName, colnames(df))
res
}
rownamesAsColumn(df.1, "area ID")
## area.ID summary.df.area.
## A A 2
## B B 3
## C C 1
The trick is to generate a data frame out of rownames(df.1)
by data.frame()
and thereby also naming the column by data.frame(newname=rownames(df.1))
.
After that, cbind()
overtakes the column names.
Upvotes: 0
Reputation: 9485
What about
df.1<-data.frame(summary(df$area))
df.1$'area ID' <- rownames(df.1)
df.1
summary.df.area. area ID
A 2 A
B 3 B
C 1 C
To order it:
df.1 <- data.frame(df.1$'area ID',df.1$ summary.df.area.)
# add whatever column names you want
colnames(df.1) <- c('ID','summary')
Upvotes: 1
Reputation: 26343
You can do
(df.1<-data.frame(area_ID = names(summary(df$area)),
summary = summary(df$area)), stringsAsFactors = FALSE)
# area_ID summary
#A A 2
#B B 3
#C C 1
Another option is stack
stack(summary(df$area))
# values ind
#1 2 A
#2 3 B
#3 1 C
But then you'd need to rename your columns obviously.
Upvotes: 1