Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

r - A newbie has a question about data frame column names

I'm new to R and I learnt data.frame today. I want to use the first row of my data frame as the column names, but the column names became really wired. Here is a sample of my data:

a <- data.frame(V1 = c("ENSMUSG00000000001_Gnai3", "0.00"), V2 = c("ENSMUSG00000000003_Pbsn", "0.00"), row.names = c("Gene_id", "P1-3-A1"))
a

The outcome is:outcome_1

I want to give the first row as my column names, so I type:

colnames(a) <- a[1,]

But the column names become like this:outcome_2

When I call the column name by using: colnames(a) ,I got this: "2" "2", instead of "ENSMUSG00000000001_Gnai3", "ENSMUSG00000000003_Pbsn"

question from:https://stackoverflow.com/questions/65878347/a-newbie-has-a-question-about-data-frame-column-names

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. How did you import the data? You should be able to fix this while importing the data itself. Maybe adding header = TRUE would be enough.

  2. While importing use stringsAsFactors = FALSE which will avoid turning string value to factors.

  3. Finally if you can't do anything in step 1 and 2 here's a way which can fix the data in your current setup.

#Assign column names
colnames(a) <- as.character(unlist(a[1,]))
#Remove 1st row
a <- a[-1, ]
#Change to respective classes
a <- type.convert(a)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...