I am new in R. I have code for changing the data frame column name. But it's not working
df<-data.frame(a=c("a","b","c"),b=c(2,4,3))
temp<-data.frame()
nam<-df[1]
i<-1
while(i<=nrow(df))
{
temp[1,i]<-df[i,2]
i<-i+1
}
colnames(temp)<-nam
Expected output is
>temp
a b c
2 4 3
You can use unlist
to transform the one-column data frame nam
into a vector:
colnames(temp) <- unlist(nam)
# a b c
# 1 2 4 3
A better way is to use [[
instead of [
when creating nam
. This will create a vector, and you don't need unlist
:
nam <- df[[1]]
colnames(temp) <- nam
By the way: You can create the new data frame based on df
in an easier way (without loops):
setNames(as.data.frame(t(df[[2]])), df[[1]])
# a b c
# 1 2 4 3
colnames(temp) = t(nam)
要么
names(temp) = t(nam)
You can change the column names with
colnames(temp) <- c("a", "b", "c")
the row names are analoguous
rownames(temp) <- c(2,4,5)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.